您好我有一个返回JSON格式的url示例。但是当我使用AFNetWorking2.0从该URL获取响应时,我没有得到正确的响应。在这里,我也发送了我的代码。
- (void)testHTTPS {
AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
[securityPolicy setAllowInvalidCertificates:YES];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager setSecurityPolicy:securityPolicy];
[manager GET:@"xxxxx"
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
NSString* newStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
}
我得到JSON Dic总是零。如果我打印“newstr”我得到html格式的响应。任何人都可以找到正确的方法吗?
我按照约翰的说法做了,但我得到了以下结果
错误:错误Domain = com.alamofire.error.serialization.response Code = -1016“请求失败:不可接受的内容类型:text / html”UserInfo = 0x7ffb39c52ed0 {com.alamofire.serialization.response.error.response = {URL:xxxxx} {状态代码:200,headers { “Cache-Control”=“public,max-age = 10800”; “Content-Encoding”= gzip; “内容长度”= 2922; “Content-Type”=“text / html”; Date =“Wed,29 Apr 2015 06:49:54 GMT”; Expires =“Wed,29 Apr 2015 09:49:55 GMT”; “Last-Modified”=“Wed,01 Apr 2015 03:19:39 GMT”; Server =“ECAcc(hhp / 9ABE)”; Vary =“Accept-Encoding”; “X-Cache”= HIT; }},NSErrorFailingURLKey = XXXXX,com.alamofire.serialization.response.error.data = LT; 0d0a3c21 444f4354 59504520 68746d6c 20505542 4c494320 222d2f2f 5733432f 2f445444 20584854 4d4c2031 2e302054 72616e73 6974696f 6e616c2f 2f454e22 20226874 74703a2f 2f777777 2e77332e 6f72672f 54522f78 68746d6c 312f4454 442f7868 746d6c31 2d747261 6e736974 696f6e61 6c2e6474 64223e0d 0a3c6874 6d6c2078 6d6c6e73 3d226874 74703a2f 2f777777 2e77332e 6f72672f 31393939 2f786874 6d6c223e 0d0a3c68 6561643e 0d0a3c6d 65746120 68747470 2d657175 69763d22 436f6e74 656e742d 54797065 2220636f 6e74656e>中NSLocalizedDescription =请求失败:不可接受的内容类型:文本/ HTML}
答案 0 :(得分:1)
问题在于您使用的是AFHTTPResponseSerializer
而不是AFNetworking的AFJSONResponseSerializer
。因此,当响应进入时,它将其解析为HTTP响应而不是JSON响应。通过将manager.responseSerializer
分配给AFJSONResponseSerializer
代替:
manager.responseSerializer = [AFJSONResponseSerializer serializer];
您会发现您不需要从响应中创建NSDictionary - 成功时它应该已经作为NSDictionary
对象发布。
查看AFNetworking 2.0 migration guide。这是一个非常方便的阅读,会让你知道将来要注意什么。