如何使用 AFJSONRequestOperation 获取 HTTP 响应
Posted
技术标签:
【中文标题】如何使用 AFJSONRequestOperation 获取 HTTP 响应【英文标题】:How to get HTTP response with AFJSONRequestOperation 【发布时间】:2013-06-12 22:00:11 【问题描述】:将 json 数据发送到服务器并希望使用 AFNetworking
从服务器获取正确的 response.statusCode
服务器:
// Helper method to send a HTTP response code/message
function sendResponse($status = 200, $body = '', $content_type = 'text/html')
$status_header = 'HTTP/1.1 ' . $status . ' ' . getStatusCodeMessage($status);
header($status_header);
header('Content-type: ' . $content_type);
echo $body;
sendResponse(200, json_encode("Files Deleted"));
ios:
NSURL *url = [NSURL URLWithString:server];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
// don't forget to set parameterEncoding!
httpClient.parameterEncoding = AFJSONParameterEncoding;\
NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:deleteExtraFilesIn parameters:nil];
[request setHTTPBody:[displayJson dataUsingEncoding:NSUTF8StringEncoding]];
[request addValue:@"ASIHTTPRequest" forHTTPHeaderField:@"User-Agent"];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSLog(@"request %@",request);
[AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/html"]];
AFHTTPRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:nil failure:nil];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id response)
// Print the response body in text
if (operation.response.statusCode == 200)
NSLog(@"Got you");
failure:^(AFHTTPRequestOperation *operation, NSError *error)
NSLog(@"Error: %@", error);
];
[operation start];
错误 NSLOG:
Error: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x1f519df0 NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.
如何在上述代码中获得正确的 http 响应?
注意:服务器上的json_encode("Files Deleted")
只是虚拟文本,我想要的是 http 响应代码。
【问题讨论】:
【参考方案1】:需要设置操作允许分片:
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:nil failure:nil];
operation.JSONReadingOptions = NSJSONReadingAllowFragments;
【讨论】:
xcode 说在“AFHTTPRequestOperation”类型的对象上找不到属性“JSONReadingoptios”,它属于哪个类? 您只需要不将实例存储为 AFHTTPRequestOperation,而是将其存储为真正的 AFJSONRequestOperation。以上是关于如何使用 AFJSONRequestOperation 获取 HTTP 响应的主要内容,如果未能解决你的问题,请参考以下文章
如何在自动布局中使用约束标识符以及如何使用标识符更改约束? [迅速]
如何使用 AngularJS 的 ng-model 创建一个数组以及如何使用 jquery 提交?