所以我从https站点发出JSON请求(在检索auth令牌后),就像AFNetworking在堆栈溢出方面的十几个其他问题一样,我得到了这个错误:
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=0x8dc2860 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
我用来提出这个请求的代码是这样的:
AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];
[requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
//Set auth header...
NSString *accessToken = [[[self.dailymileAuthentication oauthClient] accessToken] accessToken];
[requestSerializer setAuthorizationHeaderFieldWithToken:accessToken];
AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
[requestManager setRequestSerializer:requestSerializer];
[requestManager setResponseSerializer:[AFJSONResponseSerializer serializer]];
[requestManager GET:[profileURL description]
parameters:nil
success:^(AFHTTPRequestOperation *operation, id response) {
NSLog(@"JSON: %@", response);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
URL为:https://api.dailymile.com/people/me.json
如果有人有兴趣查看完整的代码库,我正在使用公共GitHub回购(注意:你不需要来理解问题,这只是可选的):https://github.com/thepost/Dailymile-iOS
我需要做什么才能发出经过身份验证的JSON请求?
我不知道我是否正确使用了AFNetworking。老实说,目前还没有太多关于AFNetworking 2的文档。
我不确定这是怎么回事;错误很明显:
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=0x8dc2860 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
DailyMile的JSON响应无效,因为它的根值没有数组或对象。
如果该值确实是JSON,并且应该被解析为JSON,那么可以将responseSerializer
的readingOptions
设置为允许片段。
然而,我怀疑API端点实际上并没有返回JSON,而是返回带有错误Content-Type
头的纯文本响应。