每当我在可变请求上设置正文并将方法设置为 POST 以外的任何内容时,该正文不会包含在请求中,并且当服务器回复时,我会收到 kCFErrorDomainCFNetwork 错误 303 (kCFErrorHTTPParseFailure)。只需将方法更改为 POST 即可确保请求顺利通过。有没有办法将主体附加到其他方法,或者我们是否坚持使用 POST 来处理所有事情?
这是提交代码:
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:assembleURL]];// cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:45.0];
#if (SERVER_TARGET_ARGS_ALLOWED==1)
[req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[req setHTTPMethod:ServerMessageMethods[operation]]; //value is @"POST" or other method name
#endif
//run the payload into a JSON
SBJsonWriter *json = [[SBJsonWriter alloc] init];
NSString *encodedPayload = [json stringWithObject:payload];
encodedPayload = [NSString stringWithFormat:@"%@", [encodedPayload stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData *dataPayload = [encodedPayload dataUsingEncoding:NSUTF8StringEncoding];
[req setHTTPBody:dataPayload];
NSURLConnection *conn = [NSURLConnection connectionWithRequest:req delegate:self];
最佳答案
我尝试查找有关它的更多最新信息,但有一篇旧帖子关于您正在谈论的确切问题:http://lists.apple.com/archives/cocoa-dev/2004/May/msg01847.html
基本上,他们提到这是代码中的错误。可悲的是,我希望能找到更新的东西来证实这一点。
我一直使用的代码是 ASIHTTPRequest它绝对可以执行 PUT 请求,因为它们使用较低级别的代码集来创建 HTTP 消息,并且不依赖 NSMutableUrlRequest
。
此外,我发现另一篇博客文章讨论了该问题以及需要为 PUT 请求添加哪些内容。 http://iphonedevelopment.blogspot.com/2008/06/http-put-and-nsmutableurlrequest.html
博客文章:
When using NSMutableURLRequest to do an HTTP PUT request, add the following line of code (req is the NSMutableURLRequest):
[req setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
That's all there is to it. If you add this line of code, your PUT requests will work just fine.
关于iphone - 当方法不是 POST 时,NSURLRequest 无法处理 HTTP 正文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3469061/