我正在使用AFNetworking库使用POST方法在服务器上发布数据。
以下是我的代码
- (void) callLoginAPI:(NSDictionary *)dictProfile{
// 1
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:[dictProfile valueForKey:@"name"], @"username",
[dictProfile valueForKey:@"first_name"],@"first_name",
[dictProfile valueForKey:@"last_name"],@"last_name",
[dictProfile valueForKey:@"email"],@"email",
[dictProfile valueForKey:@"birthday"],@"dob",
[dictProfile valueForKey:@"gender"],@"gender",
[[dictProfile valueForKey:@"location"] valueForKey:@"name"],@"location",
[dictProfile valueForKey:@"timezone"],@"timezone",
@"",@"language",
[NSString stringWithFormat:@"http://graph.facebook.com/%@/picture?type=large",[dictProfile valueForKey:@"id"]],@"profile_pic_url",
@"",@"cover_pic_url",nil];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager POST:@"http://10.1.81.35:8000/api/login/" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
}
但我在回复中遇到以下错误
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=0x797f2620 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
我无法理解代码的问题。
答案 0 :(得分:44)
问题来自响应解析。
您正在尝试反序列化JSON
响应(必须包含在NSArray
或NSDictionary
中)但是您的响应不是上述(很可能是一个简单的字符串)。
另外,尝试设置"允许片段"响应序列化器。
AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
答案 1 :(得分:14)
您可能需要身份验证才能访问JSON
响应。像这样设置身份验证:
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"XYZ" password:@"xyzzzz"];
试试这个:
AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
[self setResponseSerializer:responseSerializer];
而不是:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
答案 2 :(得分:0)
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//Request Serializer
manager.requestSerializer = [AFJSONRequestSerializer serializer];
//Response Serializer
AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
manager.responseSerializer = responseSerializer;