最近在使用AFNetworking进行网络请求时候出了一个bug解决了很久,打印error 显示Domain=NSCocoaErrorDomain Code=3840,Domain=com.alamofire.error.serialization.response Code=-1011 “Request failed:not found(404)”。一想怎么会404呢。使用的是post请求,请求代码如下:
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:EnergyManagementURL]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",nil];
[manager POST:postPath parameters:JSONObjectParameter headers:nil progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
if (handler) {
handler(responseObject);
}
} failure:^(NSURLSessionDataTask *task, NSError * error) {
if (failHandler) {
failHandler();
}
}];
后台那边没有问题,用postman测试能拿到数据,但是怎么会404呢,于是就想到会不会是在上传parameter中对manager的设置出来问题。但是发现也没有问题,使用是AFJSONRequestSerializer和AFJSONResponseSerializer而非AFHTTPRequestSerializer与AFHTTPResponseSerializer。后面在多次对照前后台传入的参数后终于找到了问题所在。原因如下:
在NSJSONWritingPrettyPrinted这个模式下,为了好看,其生成的子串是会带空格的,所以造成所编成data之后其长度变长了,服务器那边解析就会出现问题。解决方法是,把这个参数改成0即可。具体修改如下:
AFJSONRequestSerializer *rqSerializer = [AFJSONRequestSerializer serializerWithWritingOptions:0];//NSJSONWritingPrettyPrinted 设置为0
rqSerializer.stringEncoding = NSUTF8StringEncoding;
AFJSONResponseSerializer *rsSerializer = [AFJSONResponseSerializer serializer];
rsSerializer.stringEncoding = NSUTF8StringEncoding;
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:EnergyManagementURL]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",nil];
[manager POST:postPath parameters:JSONObjectParameter headers:nil progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
if (handler) {
handler(responseObject);
}
} failure:^(NSURLSessionDataTask *task, NSError * error) {
if (failHandler) {
failHandler();
}
}];
版权声明:本文为qq_37269542原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。