OGeek|极客世界-中国程序员成长平台

标题: ios - NSUrlConnection 同步请求,没有以下重定向 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 13:46
标题: ios - NSUrlConnection 同步请求,没有以下重定向

问题

我需要执行一个同步 HTTP 请求,不跟随重定向,最好不使用实例变量,因为这将被合并到 j2objc项目。

我尝试了什么

我尝试过使用 NSURLConnection sendSynchronousRequest,很遗憾不能轻易告诉它不要遵循重定向。

背景

在告诉我不应该使用同步请求之前,请记住这段代码是为了模拟 Java 的 HttpUrlConnection ,对于 j2objc 而言,其行为本质上是同步的项目。 IosHttpUrlConnections' native makeSynchronousRequest的执行目前始终遵循重定向。它应该尊重 HttpUrlConnection.instanceFollowRedirects field .

进行了进一步研究

希望你能帮助我



Best Answer-推荐答案


你可以使用带有信号量的 NSURLSession,像这样创建:

dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];
NSURLSessionTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

    if (data)
    {
        // do whatever you want with the data here
    }
    else
    {
        NSLog(@"error = %@", error);
    }

    dispatch_semaphore_signal(semaphore);
}];
[task resume];

// but have the thread wait until the task is done

dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

你必须实现下面的NSURLSessionTaskDelegate方法,并调用completionHandler block 传递null来停止重定向。

- (void)URLSessionNSURLSession *)session
              taskNSURLSessionTask *)task
willPerformHTTPRedirectionNSHTTPURLResponse *)response
        newRequestNSURLRequest *)request
 completionHandlervoid (^)(NSURLRequest *))completionHandler

关于ios - NSUrlConnection 同步请求,没有以下重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27961107/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4