美文网首页
AFNetworking POST发送 x-www-form-u

AFNetworking POST发送 x-www-form-u

作者: Superman168 | 来源:发表于2018-04-19 00:03 被阅读0次
    前言

    今日上午,与新的后台调试接口,死活调不通,一直报错,如下:
    error = Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: bad request (400)" UserInfo={NSLocalizedDescription=Request failed: bad request (400),
    这种错误要么是请求的方式不对,要么是参数后台识别不了。经与后台一番唾沫之后,后台说只能接受 x-www-form-urlencoded 这种格式的参数,好吧!也是第一次见,于是就开始各种尝试。

    科普

    HTTP POST 请求提交数据有四种方式,具体可以参考Http POST 提交数据的四种方式解析。AFN 默认的方式是 multipart/form-data,而目前的服务器不支持,需要以application/x-www-form-urlencoded 方式提交

    解决历程

    其实作为iOS 开发者来说,最常用的应该是 application/json,就想起初简单封装的 AFN 的初始化是这样的,

        NSURL *url = [NSURL URLWithString:BASE_URL];
        _manager = [[self alloc] initWithBaseURL:url];
        _manager.requestSerializer = [AFJSONRequestSerializer serializer];
        [_manager.requestSerializer setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        _manager.securityPolicy.allowInvalidCertificates = YES;
        _manager.securityPolicy.validatesDomainName = NO;
        _manager.requestSerializer.timeoutInterval = 15;
        NSSet *set = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/xml", @"text/plain", nil];
        _manager.responseSerializer.acceptableContentTypes =[_manager.responseSerializer.acceptableContentTypes setByAddingObjectsFromSet:set];        
        });
    

    肯定不行了,后改为这样:

           NSURL *url = [NSURL URLWithString:BASE_URL];
           _manager = [[self alloc] initWithBaseURL:url];
           _manager.requestSerializer = [AFJSONRequestSerializer serializer];
           [_manager.requestSerializer setValue:@"application/x-www-form-urlencoded;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
           _manager.securityPolicy.allowInvalidCertificates = YES;
           _manager.securityPolicy.validatesDomainName = NO;
           _manager.requestSerializer.timeoutInterval = 15;
           NSSet *set = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/xml", @"text/plain", nil];
           _manager.responseSerializer.acceptableContentTypes =[_manager.responseSerializer.acceptableContentTypes setByAddingObjectsFromSet:set];
    

    没想到依然报错,实在是没有办法,最终发现罪魁祸首就是这句:

         _manager.requestSerializer = [AFJSONRequestSerializer serializer];
    

    注意:记住:千万不要设置request为json格式,千万不要加这行代码!!!

    好了,记录一下,相互学习!

    (参照 AFNetworking怎么post x-www-form-urlencoded类型的数据

    相关文章

      网友评论

          本文标题:AFNetworking POST发送 x-www-form-u

          本文链接:https://www.haomeiwen.com/subject/cycikftx.html