最近iOS开发中,客户端需要使用http POST去进行请求服务器。需要发送的是XML格式的,当然接收的也是XML。我们准备使用的是AFNetworking来实现。关于AFnetworking的使用以及Cocoapods包管理,请参考我的其他几篇博客:《iOS项目开发实战——使用AFNetworking进行Http Get请求》,《查看进行AFNetworking请求时的头部信息》,《iOS包管理工具Cocoapods的安装与使用》。
我进行请求的代码实现如下:[objc] view plain copy print?
-(void)query05{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"]; NSString *str = @"" "" "****" "***" "***" "***" "";
NSDictionary *parameters = @{@"test":str};
[manager POST:@"http://***.php"parameters:parameters success:^(AFHTTPRequestOperation *operation,id responseObject) { NSLog(@"Success: %@", responseObject); }failure:^(AFHTTPRequestOperation *operation,NSError *error) { NSLog(@"Error: %@", error); }]; } 但是当运行程序后,出现如何错误:Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}如图:。 这个bug的确很诡异,我根本没有做任何关于JSON的操作,却给我报了一个JSON的错。最后查了很多资料,解决方案如下:主要是增加了几行代码:[html] view plain copy print?- (void)query05{ //增加这几行代码; AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init]; [securityPolicy setAllowInvalidCertificates:YES]; AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; [html] view plain copy print?//这里进行设置; [manager setSecurityPolicy:securityPolicy]; manager.responseSerializer = [AFHTTPResponseSerializer serializer]; NSString *str = @"" "" "***" "***" "***" "***" ""; NSDictionary *parameters = @{@"test" : str}; [manager POST:@"http://***.php" parameters:parameters success:^(AFHTTPRequestOperation *operation,id responseObject){ NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]; NSLog(@"成功: %@", string); } failure:^(AFHTTPRequestOperation *operation,NSError *error){ NSLog(@"失败: %@", error); }]; } 通过以上的修改,就能成功的获得服务器的数据了。
原文:链接http://blog.csdn.net/chenyufeng1991/article/details/49980205