使用AFNetWorking发送请求时遇到问题

时间:2014-09-08 19:28:44

标签: ios objective-c afnetworking asihttprequest

AFNetworking似乎对我不起作用。特别是当我向服务器发送apiKey请求时,它会给我一个未经授权的错误。然而,ASIHTTPRequest对我来说很好,所以在AFNetWorking中似乎有些错误。我知道问题是发送apiKey因为如果我评论它AFNetWork正常工作。我仍然需要发送API密钥。任何帮助将不胜感激。

AFNetWorking

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setValue:apiKey forHTTPHeaderField:@"apiKey"];
NSMutableDictionary *userinfo = [[NSMutableDictionary alloc] init];
[manager POST:urlStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    [operation setUserInfo:userinfo];  
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    [operation setUserInfo:userinfo];
}];
}

ASIHTTPRequest

  NSString *urlStr = [NSString stringWithFormat:@"%@/%@", submitReportUrl, [self urlEncode:path]];
 ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlStr]];
 [request setDelegate:self];
 NSMutableDictionary *userinfo = [[NSMutableDictionary alloc] init];
 [userinfo setObject:NSStringFromSelector(self.didFinishSelector) forKey:@"didFinishSelector"];
 [userinfo setObject:NSStringFromSelector(self.didFailSelector) forKey:@"didFailSelector"];
 [request setUserInfo:userinfo];
 [request addRequestHeader:@"apiKey" value:apiKey];
 [request setRequestMethod:method];
  NSArray *keys = [params allKeys];
  for ( NSString *key in keys )
        [request addPostValue:[params objectForKey:key] forKey:key];
 [self.operationQueue addOperation:request];

1 个答案:

答案 0 :(得分:1)

manager.requestSerializer = [AFJSONRequestSerializer serializer]; 

我在使用帖子时遇到了同样的问题。所以研究问题在哪里。如果你没有添加代码的约行。 AFNetworking将自动添加标题

内容类型:" text / html" 任意一个 Cotent-Type:" text / plain"

通过添加上面的代码变成 Content-Type:" application / json"

所以问题解决了。由于服务器期待JSON。