我将以下消息发送到AFHTTPClient的实例.我希望成功块被发送一个Foundation对象(一个字典),但调试器告诉我JSON是一个_NSCFData对象. 关于SO的这个问题表明我需要将Accept标头设置为'application/json'.好吧,我正在这样做,但AFNetworking仍然没有在响应体中解码JSON.如果我使用NSJSONSerialization自己解码json,我会得到一个我期望的NSDictionary.我究竟做错了什么?
[client setDefaultHeader:@"Accept" value:@"application/json"];
[client postPath:@"/app/open_connection/"
parameters:params
success:^(AFHTTPRequestOperation *operation, id JSON) {
NSLog(@"successful login! %@", [JSON valueForKeyPath:@"status"]);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error opening connection");
NSAlert *alert = [NSAlert alertWithError:error];
[alert runModal];
}
];
Run Code Online (Sandbox Code Playgroud)
注意:我正在使用Django在Python中编写服务器.响应的内容类型是'application/json'
当您使用AFHTTPClientJSON API时,通常需要设置所有这三个设置:
httpClient.parameterEncoding = AFJSONParameterEncoding;
[httpClient setDefaultHeader:@"Accept" value:@"application/json"];
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
Run Code Online (Sandbox Code Playgroud)
现在,当您使用客户端发出请求时,它将知道将响应解析为JSON.
[httpClient postPath:@"/app/open_connection/"
parameters:params
success:^(AFHTTPRequestOperation *operation, id response) {
NSLog(@"JSON! %@", response);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
Run Code Online (Sandbox Code Playgroud)
这也是我发现的一个技巧.在NSError对象中,您可以解析它并检索错误消息(如果HTTP响应有JSON错误消息):
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSDictionary *JSON =
[NSJSONSerialization JSONObjectWithData: [error.localizedRecoverySuggestion dataUsingEncoding:NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error:nil];
failureCallback(JSON[@"message"]);
}
Run Code Online (Sandbox Code Playgroud)
试试这个...我认为您的客户端设置可能有问题。
NSMutableURLRequest *request = [client requestWithMethod:@"POST" path:@"/app/open_connection/" parameters:params];
AFJSONRequestOperation *operation =
[AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(@"successful login! %@", [JSON valueForKeyPath:@"status"]);
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(@"error opening connection");
NSAlert *alert = [NSAlert alertWithError:error];
[alert runModal];
}];
[operation start];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3751 次 |
| 最近记录: |