AFNetworking接受内容类型错误:{NSDebugDescription = JSON文本不以数组或对象开头,并且选项允许未设置片段。}

时间:2015-06-24 04:50:13

标签: afnetworking

我正在使用AFNetworking获取普通/文本:

    let manager = AFHTTPRequestOperationManager()

    manager.GET(url, parameters: nil, success: { (op: AFHTTPRequestOperation!, res: AnyObject!) -> Void in

        },failure: { (op: AFHTTPRequestOperation!, er:NSError!) -> Void in
        println(op,er)

    })

接受内容类型:

manager.responseSerializer.acceptableContentTypes
[text/javascript, application/json, text/json]

所以我在失败块中遇到错误:

NSLocalizedDescription=Request failed: unacceptable content-type: text/plain}

然后我以这种方式添加了text / plain:

var set = manager.responseSerializer.acceptableContentTypes
set.insert("text/plain")
manager.responseSerializer.acceptableContentTypes = set

现在的类型是:

manager.responseSerializer.acceptableContentTypes
[application/json, text/javascript, text/plain, text/json]

但是我得到了新的错误:

{ URL: http://192.168.1.9:8081/sec.jsp } { status code: 200, headers {
"Content-Length" = 44;
"Content-Type" = "text/plain; charset=utf-8";
Expires = "Thu, 01 Jan 1970 00:00:00 GMT";
Server = "Jetty(6.1.10)";
"Set-Cookie" = "JSESSIONID=tapmhct7hanv;Path=/";
} }>, Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x7fda31fb4a90 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.})

我认为问题是因为JSON无法读取响应。但我已将其设置为text / plain,它是否仍尝试将纯文本解析为JSON?

我搜索并尝试了一种方式:

manager.responseSerializer = AFJSONResponseSerializer(readingOptions: NSJSONReadingOptions.AllowFragments)

但错误是:

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Garbage at end.) UserInfo=0x7ff4b1790660 {NSDebugDescription=Garbage at end.})

2 个答案:

答案 0 :(得分:10)

伙计,这是我在配置AFNetworking课程时添加的内容,并且工作正常。

你得到那个3840错误的原因是因为你的API服务器返回一个整数甚至空的东西,ios json解析器失败了。

你能否迅速确定你正在使用的短语是否正确?

  

_delegateClient.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];

答案 1 :(得分:5)

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer
serializerWithReadingOptions:NSJSONReadingAllowFragments];

[manager GET:url parameters:parameters progress:nil

         success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             NSLog(@"request: %@\n", responseObject);
             completionBlock(responseObject,nil);
         }
         failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
             NSLog(@"Error: %@\n", error);
             completionBlock(nil,error);
         }];