AFNetworking 2.0//Как читать заголовок ответа

Я использую новую версию AFNetworking, и я не могу понять, как читать заголовки ответа. Я использую AFHTTPSessionManager для выполнения моего запроса, все работает хорошо, но я не могу найти поле ответа заголовка.

Вот как я продолжаю

     self.sessionManager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:BASE_URL]];
     [self.sessionManager GET:urlId parameters:nil
                      success:^(NSURLSessionDataTask *task, id responseObject) {

                          if ([self.delegate respondsToSelector:@selector(userIsLoadedWithInfos:)]) {
                              [self.delegate userIsLoadedWithInfos: responseObject];
                          }
                      } failure:^(NSURLSessionDataTask *task, NSError *error) {
                          if ([self.delegate respondsToSelector:@selector(userLoadingFailed)]) {
                              [self.delegate userLoadingFailed];
                          }
                      }
         ];

Я пытаюсь прочитать атрибут ответа задачи, но он возвращает NSURLResponse, который не включает заголовки. Кто-нибудь теперь, как читать заголовки ответов с версией 2.0? Благодаря

Ответы

Ответ 1

Вы пытались получить заголовки из NSURLResponse, который возвращается,

Вы можете попробовать что-то вроде объекта NSURLResponse,

NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
if ([httpResponse respondsToSelector:@selector(allHeaderFields)]) {
    NSDictionary *dictionary = [httpResponse allHeaderFields];
    NSLog([dictionary description]);
}

Надеюсь, это поможет вам.!

Ответ 2

немного более надежный код, чем у Viruss mcs:

if ([task.response isKindOfClass:[NSHTTPURLResponse class]]) {
    NSHTTPURLResponse *r = (NSHTTPURLResponse *)task.response;
    NSLog(@"%@" ,[r allHeaderFields]);
}

возвращает

{
    Connection = "Keep-Alive";
    "Content-Length" = 12771;
    "Content-Type" = "application/json";
    Date = "Fri, 06 Dec 2013 10:40:48 GMT";
    "Keep-Alive" = "timeout=5";
    "Proxy-Connection" = "Keep-Alive";
    Server = "gunicorn/18.0";
}

Аналогичным образом вы можете заверить, что кастинг выполняется с помощью [response respondsToSelector:@selector(allHeaderFields)], но вы также должны вызвать это, прежде чем выполнять бросок

if ([task.response respondsToSelector:@selector(allHeaderFields)]) {
    NSHTTPURLResponse *r = (NSHTTPURLResponse *)task.response;
    NSLog(@"%@" ,[r allHeaderFields]);
}

или вообще не выполняется:

if ([task.response respondsToSelector:@selector(allHeaderFields)]) {
    NSLog(@"%@" ,[task.response performSelector:@selector(allHeaderFields)]);
}

Ответ 3

Интересно, что приведенные выше ответы показывают, что параметр id responseObject возвращает NSURLResponse. Я использую сервер JAX-RS на бэкэнд, и я получаю другой ответ. При выполнении команды curl на моем сервере, мой ответ таков:

$ curl -v "http://10.0.1.8:3000/items"
* About to connect() to 10.0.1.8 port 3000 (#0)
*   Trying 10.0.1.8...
* Adding handle: conn: 0x7f9f51804000
* Adding handle: send: 0
* Adding handle: recv: 0
* Curl_addHandleToPipeline: length: 1
* - Conn 0 (0x7f9f51804000) send_pipe: 1, recv_pipe: 0
* Connected to 10.0.1.8 (10.0.1.8) port 3000 (#0)
> GET /items HTTP/1.1
> User-Agent: curl/7.30.0
> Host: 10.0.1.8:3000
> Accept: */*
>
< HTTP/1.1 200 OK
< ETag: af0057e2-1c6d-4a47-b81a-a754238b60fd
< Content-Type: application/json
< Content-Length: 255
< Connection: keep-alive
<
* Connection #0 to host 10.0.1.8 left intact
[{"name":"Item1","uid":"F465AAD2-AA39-4C33-A57A-F0543C25C476"},
 {"name":"Item2","uid":"6505A82E-A473-4A7D-BC4B-BCBEFFFE8E9C"}]

My responseObject - это массив элементов в ответе сервера, а не NSURLResponse. Вот как я получил заголовки:

void (^handleSuccess)(NSURLSessionDataTask *, id) = ^(NSURLSessionDataTask *task, id responseObject) {
    // handle response headers
    NSHTTPURLResponse *response = ((NSHTTPURLResponse *)[task response]);
    NSDictionary *headers = [response allHeaderFields];

    // handle response body
    NSArray *responseItems = responseObject;
    for (NSDictionary *item in responseItems) {
        [self.activeDataController createObject:item];
    }
};

Ответ 4

Я подклассифицирован AFHTTPRequestOperationManager и использую:

- (AFHTTPRequestOperation *)POST:(NSString *)URLString
                      parameters:(NSDictionary *)parameters
                         success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                         failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;

для большинства моих запросов веб-сервисов. При использовании этого метода заголовки ответов будут частью объекта операции. Что-то вроде этого:

[self POST:url parameters:newParams success:^(AFHTTPRequestOperation *operation, id responseObject) {
    // Response headers will be a dictionary
    NSDictionary *headers = operation.response.allHeaderFields;
...

Ответ 5

Для быстрого 2.0:

if let response = operation.response {
    print(response.allHeaderFields)
}