2015-11-22 19:31:11 CHENYUFENG1991 阅读数 37606

     由于最近忙着开发项目,好几天没来写博客了。我把最近遇到的一个小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  。欢迎大家访问!

2016-03-04 15:44:54 qq_30402119 阅读数 4703

使用最新版本的AFN 进行HTTP的网络请求偶尔遇到的问题, 有时候自己就解决了, 也不知道原因, 后来 stackOverFlow上看到一个答案试了一下 可以解决 不过他的都是用C 写的, 简单改了一下 还是使用AFN

代码

/* 主要就是给 请求的过程添加一个安全政策的对象 并使用 */
+ (void)POSTWithURL:(NSString *)url withBody:(id)body withBodyStyle:(bodyStyle)bodyStyle withHttpHead:(NSDictionary *)head responseStyle:(responseStyle)style withSuccess:(void (^)(id))success withFail:(void (^)(NSError *))fail {

    AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
    [securityPolicy setAllowInvalidCertificates:YES];

    NSString *url_string = [NSString stringWithString:url];
    /* 创建http请求管理者 */
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    /* 处理body类型 */
    switch (bodyStyle) {
        case stringStyle: {
            break;
        }
        case JSONStyle: {
            break;
        }
    }

    /* 添加请求头 */
    if (head) {
        for (NSString *key in head) {
            [manager.requestSerializer setValue:head[key] forHTTPHeaderField:key];
        }
    }
    /* 判断返回数据类型 */
    switch (style) {
        case DATA: {
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            break;
        }
        case JSON: {
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            break;
        }
        case XML: {
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        }

        default:
            break;
    }
    /* 设置请求接受的数据类型 */
    [manager setSecurityPolicy:securityPolicy];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

//    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil]];
    //本地缓存设置,沙盒路径设置
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *pathString = path.lastObject;
    NSString *pathLast =[NSString stringWithFormat:@"/Caches/com.hackemist.post.default/%lu.text", (unsigned long)[url_string hash]];

    //创建字符串文件存储路径
    NSString *PathName =[pathString stringByAppendingString:pathLast];

    //第一次进入判断有没有文件夹,如果没有就创建一个
    NSString * textPath = [pathString stringByAppendingFormat:@"/Caches/com.hackemist.post.default"];
    if (![[NSFileManager defaultManager]fileExistsAtPath:textPath]) {

        [[NSFileManager defaultManager]createDirectoryAtPath:textPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    //设BOOL值 判断解析后的数据是数组还是字典
    __block  BOOL isClass = NO;


    /* POST请求 */
    [manager POST:url parameters:body constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

    } progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject isKindOfClass:[NSArray class]]) {
            isClass = YES;
        } else{
            isClass = NO;
        }
        [responseObject writeToFile:PathName atomically:YES];
        success(responseObject);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSString * cachePath = PathName;
        if ([[NSFileManager defaultManager] fileExistsAtPath:cachePath]) {
            //从本地读缓存文件
            id responseObject = nil;
            if (isClass) {
                responseObject = [NSMutableArray arrayWithContentsOfFile:cachePath];
            } else {
                responseObject = [NSMutableDictionary dictionaryWithContentsOfFile:cachePath];
            }
            success(responseObject);
        }

    }];
}

本篇和之前写过的关于AFN封装的博客挂钩 如果不懂可以参考一下

http://blog.csdn.net/qq_30402119/article/details/49822513主要就是加下面的四句

    /* 设置安全政策对象 */
     AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
    [securityPolicy setAllowInvalidCertificates:YES];
    /* 使用 */
    [manager setSecurityPolicy:securityPolicy];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
2016-06-16 15:22:00 baide1206 阅读数 10

    let url:NSURL = NSURL(string: "http://flash.weather.com.cn/wmaps/xml/shanghai.xml")!

    let request:NSURLRequest = NSURLRequest(URL: url)

    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response:NSURLResponse?,data:NSData?,error:NSError?) in

          if(error==nil || data?.length > nil){

//            let testString : String = String(data: data!, encoding: NSUTF8StringEncoding)!

            //数据转换为xml类型

            let weather = NSXMLParser(data:data!)

            weather.delegate = self

            weather.parse()

//            self.requestContent.text=testString

          }

    })

转载于:https://www.cnblogs.com/ZHANYU/p/5591113.html

2016-04-28 01:14:10 asuno_1 阅读数 1218

最近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.}

如图:

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


     这个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
。欢迎大家访问!

2015-05-20 12:30:00 weixin_33909059 阅读数 8


声明 
欢迎转载,但请保留文章原始出处:) 
博客园:http://www.cnblogs.com
农民伯伯: http://over140.cnblogs.com

 

正文

同样的代码在iOS8下没有问题,iOS7就取不到数据(会包Cocoa Error 3840之类的错误),跟踪发现请求Head参数设置不管用,根据文字底部的参考改了一下兼容代码:

    private func getRequest(method: Method, _ URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil) -> NSMutableURLRequest {
        let request = NSMutableURLRequest(URL: NSURL(string: URLString.URLString)!)
        request.HTTPMethod = method.rawValue
        if parameters != nil {
            request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters!, options: nil, error: nil)
        }
        request.setValue(API_UA, forHTTPHeaderField: "User-Agent")
        request.setValue(HEADER_ACCEPT, forHTTPHeaderField: "Accept")
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        
        return request
    }

这里API_UA和HEADER_ACCEPT更改为自己的Head参数即可,使用代码:

        var request: Request!
        if DeviceUtils.isIOS7() {
            request =  mHttpManager.request(getRequest(method, URLString, parameters: parameters))
        } else {
            request = mHttpManager.request(method, URLString , parameters: parameters, encoding: ParameterEncoding.JSON)
        }
        //request.responseJSON....

代码说明:

a)、 mHttpManager就是Manager.sharedInstance,注意别忘了设置mHttpManager.session.configuration.HTTPAdditionalHeaders,在iOS8下还是管用的

 

参考:

Setting Custom HTTP Headers in Alamofire in iOS 7 not working 

(参考帖子,也尝试设置NSURLSessionConfiguration但是没有效果 

 

结束

继续iOS,继续swift,继续遇到问题解决问题。 

转载于:https://www.cnblogs.com/over140/p/4516862.html

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