ios - NSUrlConnection 同步请求,没有以下重定向
<p><h3>问题</h3>
<p>我需要执行一个同步 HTTP 请求,不跟随重定向,最好不使用实例变量,因为这将被合并到 <a href="https://github.com/google/j2objc" rel="noreferrer noopener nofollow">j2objc</a>项目。</p>
<h3>我尝试了什么</h3>
<p>我尝试过使用 <code>NSURLConnection sendSynchronousRequest</code>,很遗憾不能轻易告诉它不要遵循重定向。</p>
<h3>背景</h3>
<p>在告诉我不应该使用同步请求之前,请记住这段代码是为了模拟 Java 的 <a href="http://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html" rel="noreferrer noopener nofollow"><code>HttpUrlConnection</code></a> ,对于 <a href="https://github.com/google/j2objc" rel="noreferrer noopener nofollow">j2objc</a> 而言,其行为本质上是同步的项目。 <a href="https://github.com/google/j2objc/blob/b4f2f441225056d0b372badd4e560e5957adcc1e/jre_emul/Classes/com/google/j2objc/net/IosHttpURLConnection.java#L312" rel="noreferrer noopener nofollow"><code>IosHttpUrlConnections</code>' native <code>makeSynchronousRequest</code></a>的执行目前始终遵循重定向。它应该尊重 <a href="http://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html#instanceFollowRedirects" rel="noreferrer noopener nofollow"><code>HttpUrlConnection.instanceFollowRedirects</code> field</a> .</p>
<h3>进行了进一步研究</h3>
<ul>
<li>在异步模式下使用 NSUrlConnection 时,会调用委托(delegate)方法,该方法允许启用/禁用重定向。但是,我需要同步操作。</li>
<li> <a href="https://stackoverflow.com/a/22329855/477854" rel="noreferrer noopener nofollow">This answer on NSUrlconnection: How to wait for completion</a>展示了如何使用异步请求实现 <code>sendSynchronousRequest</code>。但是,我无法修改它以使用委托(delegate),因此无法不遵循重定向。</li>
</ul>
<h3>希望你能帮助我</h3></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>你可以使用带有信号量的 NSURLSession,像这样创建:</p>
<pre><code>dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
NSURLSessionConfiguration *sessionConfiguration = ;
NSURLSession *session = ;
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);
}];
;
// but have the thread wait until the task is done
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
</code></pre>
<p>你必须实现下面的<code>NSURLSessionTaskDelegate</code>方法,并调用completionHandler block 传递null来停止重定向。</p>
<pre><code>- (void)URLSession:(NSURLSession *)session
task:(NSURLSessionTask *)task
willPerformHTTPRedirection:(NSHTTPURLResponse *)response
newRequest:(NSURLRequest *)request
completionHandler:(void (^)(NSURLRequest *))completionHandler
</code></pre></p>
<p style="font-size: 20px;">关于ios - NSUrlConnection 同步请求,没有以下重定向,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/27961107/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/27961107/
</a>
</p>
页:
[1]