iphone - 当方法不是 POST 时,NSURLRequest 无法处理 HTTP 正文?

标签 iphone cocoa nsurlrequest

每当我在可变请求上设置正文并将方法设置为 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/

相关文章:

jquery 元素在 ios 上过渡和滚动后闪烁

cocoa - 多个对象上的 NSNotification

iphone - NSURLErrorDomain 错误-1012

ios - 不允许我发布到此 API 的 NSURLSession 我做错了什么?

iphone - 如何在 PieChart 中给每个切片 Coreplot iphone 命名?

iphone - AudioUnit的奇怪缓慢录音

cocoa - C++下创建NSWindow

cocoa - Xcode 3.2 中缺少 "find options"

ios - 如何正确编码 URL 字符串

android - Android 上的 phonegap 换行警报