xcode 读取 AFNetworking 响应标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12351464/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 01:26:50  来源:igfitidea点击:

Reading AFNetworking response headers

objective-cxcodeafnetworking

提问by lix

I'm trying to figure out how to read the response headers from a AFNetworking request?

我想弄清楚如何从 AFNetworking 请求中读取响应标头?

Is it possible in the following snippet, or do I need to take another approach?

是否可以在以下代码段中使用,或者我是否需要采取其他方法?

// Create client
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://example.com/"]];

// Send request
[client getPath:@"/test" parameters:nil success:^(AFHTTPRequestOperation *operation, id response) {

} failure:^(AFHTTPRequestOperation *operation, NSError *error){

}];

回答by Bart Jacobs

The easiest way to accomplish this is to use the response property (not the response object of the block) of the AFHTTPRequestOperation instance that is available in both the success and failure blocks.

完成此操作的最简单方法是使用 AFHTTPRequestOperation 实例的响应属性(而不是块的响应对象),该实例在成功和失败块中均可用。

This response object is an instance of NSHTTPURLResponseand you can send it a message of allHeaderFieldsto fetch all the headers of your request.

这个响应对象是NSHTTPURLResponse 的一个实例,你可以向它发送一条消息 allHeaderFields来获取你请求的所有标头。

回答by brandonscript

Quite simply, since the accepted answer doesn't actually have an example:

很简单,因为接受的答案实际上没有一个例子:

[operationInstance setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
       NSLog(@"%@", operation.response.allHeaderFields);
}];

回答by Ashish Srivastava

I was not able to resolve it by [[operation response] allHeaderFields]or operation.response.allHeaderFields, as it gave compilation error.

我无法通过[[operation response] allHeaderFields]或解决它 operation.response.allHeaderFields,因为它给出了编译错误。

I just typecasted it to (NSDictionary *)and access the key values as

我只是将它的类型转换为(NSDictionary *)并访问键值

[[(NSDictionary *)operation valueForKey: @"response"] valueForKey: @"allHeaderFields"]

[[(NSDictionary *)operation valueForKey: @"response"] valueForKey: @"allHeaderFields"]

回答by Vinay Krishna Gupta

NSDictionary *responseheaders = [HTTPResponse allHeaderFields];
NSString *newtoken = [responseheaders valueForKey:@"Authorization"];