无法将自定义http标头字段添加到NSMutableURLRequest

时间:2017-10-12 19:22:33

标签: ios objective-c http post nsmutableurlrequest

我正在尝试通过addValue向POST请求添加自定义标头字段“jsonParams”,如下所示:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:120.0];

[request setHTTPMethod:@"POST"];

[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params
                                                   options:NSJSONWritingPrettyPrinted
                                                     error:&error];


NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];


[request addValue:jsonString forHTTPHeaderField:@"jsonParams"];

NSData *bodyData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
[request setHTTPBody:bodyData];

但是,“jsonParams”字段未添加到标题字段中。但是,如果我将jsonString中的值更改为@“test”之类的字符串对象,它可以正常工作。有什么想法吗?

0 个答案:

没有答案