NSMutableURLRequest设置HttpBody删除Header参数



我试图在Objective-C中的POST请求上传递两个不同的参数。

第一个参数应该放在Header上,而另一个应该放在Body上。

NSDictionary *headerParams = [NSDictionary dictionaryWithObjectsAndKeys:
                                    @"password", @"grant_type",
                                    @"write", @"scope", nil];
NSDictionary *bodyParams = [NSDictionary dictionaryWithObjectsAndKeys:
                                    username, @"username",
                                    password, @"password", nil];
AFHTTPRequestSerializer *r = [AFHTTPRequestSerializer serializer];
NSError *error = nil;
NSData *requestBody = [NSKeyedArchiver archivedDataWithRootObject:bodyParams];
NSMutableURLRequest *request = [r requestWithMethod:@"POST" URLString:urlString parameters:headerParams error:&error];
[request setValue:[NSString stringWithFormat:@"application/json,application/x-www-form-urlencoded"] forHTTPHeaderField:@"Accept"];
[request setValue:[NSString stringWithFormat:@"application/x-www-form-urlencoded"] forHTTPHeaderField:@"ContentType"];
[request setHTTPBody: requestBody]; //--> If I comment this, the headerParams doesn't removed

如果我用以下语句调试上面的代码:

po [[NSString alloc] initWithData: request.HTTPBody encoding:4]

我得了nil。但是当我省略[request setHTTPBody: requestBody];的部分时,我得到了headerParams的值。我想得到headerParamsbodyParams的值。怎么了?谢谢

通过查看AFHTTPRequestSerializer关于parameters参数的文档:

参数
要设置为GET请求的查询字符串或请求HTTP正文的参数。

你认为会进入请求头部的字典实际上会进入它的主体。代码最后一行的setHTTPBody:调用将覆盖此值。

如果希望第一个headerParams字典进入请求头,则需要使用setValue:forHTTPHeaderField:

最新更新