macos 在 Cocoa 中通过 NSURLRequest/NSURLConnection 接收 HTTP 标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/237164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Receive HTTP Headers via NSURLRequest/NSURLConnection in Cocoa
提问by Ben Gottlieb
I've been working on figuring out how to receive HTTP Headers via a request made with NSURLConnection. Typically a request is made with something as simple as the following:
我一直在研究如何通过 NSURLConnection 发出的请求来接收 HTTP 标头。通常,一个请求是通过如下简单的方式发出的:
NSURLConnection *connection = [[NSURLConnection alloc]
initWithRequest:request
delegate:self];
The only way I've personally found in Apple's abundant documentation to receive response headers is via a synchronous call using the following NSURLConnection class method:
我个人在 Apple 丰富的文档中发现接收响应标头的唯一方法是使用以下 NSURLConnection 类方法通过同步调用:
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error
Here I can easily reference a response object of type NSURLResponse. The problem here is that I'm not ready to make synchronous requests via a mobile device, especially with a network that has high latency such as EDGE. Is it possible to get similar results with the default, asynchronous behavior of NSURLConnection?
在这里,我可以轻松引用 NSURLResponse 类型的响应对象。这里的问题是我还没有准备好通过移动设备发出同步请求,尤其是对于具有高延迟的网络,例如 EDGE。是否可以通过 NSURLConnection 的默认异步行为获得类似的结果?
回答by Ben Gottlieb
In your connection delegate, add the -connection:didReceiveResponse:
method. If you're doing a standard HTTP request, the NSURLResponse object passed in will actually be an NSHTTPURLResponse object, and responds to the -allHeaderFields
message. This should be what you're looking for.
在您的连接委托中,添加该-connection:didReceiveResponse:
方法。如果您正在执行标准 HTTP 请求,则传入的 NSURLResponse 对象实际上将是一个 NSHTTPURLResponse 对象,并响应-allHeaderFields
消息。这应该是你要找的。