iOS开发Post请求错误:Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or ...

版权声明:本文为博主原创文章,欢迎分享到其它技术社区,分享请标明出处: https://blog.csdn.net/CHENYUFENG1991/article/details/49980205

     由于最近忙着开发项目,好几天没来写博客了。我把最近遇到的一个小bug来和大家分享一下。

     最近iOS开发中,客户端需要使用http POST去进行请求服务器。需要发送的是XML格式的,当然接收的也是XML。我们准备使用的是AFNetworking来实现。关于AFnetworking的使用以及Cocoapods包管理,请参考我的其他几篇博客:《iOS项目开发实战——使用AFNetworking进行Http Get请求》,《查看进行AFNetworking请求时的头部信息》,《iOS包管理工具Cocoapods的安装与使用》。我进行请求的代码实现如下:

-(void)query05{

  AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
  
  manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
  
  NSString *str = @"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  "<root>"
  "<command_type>****</command_type>"
  "<id>***</id>"
  "<action>***</action>"
  "<value>***</value>"
  "</root>";
  
  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的错。最后查了很多资料,解决方案如下:主要是增加了几行代码:

- (void)query05{
  
  //增加这几行代码;
  AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
  [securityPolicy setAllowInvalidCertificates:YES];
  
  AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//这里进行设置;
  [manager setSecurityPolicy:securityPolicy];
  manager.responseSerializer = [AFHTTPResponseSerializer serializer];
  
  NSString *str = @"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  "<root>"
  "<command_type>***</command_type>"
  "<id>***</id>"
  "<action>***</action>"
  "<value>***</value>"
  "</root>";
  
  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);
        }];
}


    通过以上的修改,就能成功的获得服务器的数据了。



github主页:https://github.com/chenyufeng1991  。欢迎大家访问!

没有更多推荐了,返回首页