无法使用NSURLConnection使iOS http post正常工作

5

我试图让POST消息正常工作。我看过一些描述如何做到这一点的帖子,比如这篇,但我仍然无法使其正常工作。以下是我的Objective-C代码:

NSString * urlString = @"http://magicthegatheringdatabase.com/test.php";
NSURL *aUrl = [NSURL URLWithString: urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:60.0];

NSString *postString = [NSString stringWithFormat:@"tes1=%@&test2=%@",
                        [@"hello" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                        [@"world" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData * postBody = [postString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody: postBody];

[request addValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

NSString *postLength = [NSString stringWithFormat:@"%d", postBody.length];
[request addValue: postLength forHTTPHeaderField:@"Content-Length"];

[request setHTTPMethod:@"POST"];

NSError * error = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request
                                           returningResponse: nil
                                                       error: &error];
NSLog(@"%p, %@", error, error.localizedDescription);

NSString * returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"Result: %@", returnString);

这里是我的PHP代码:

<?php
  print_r($_REQUEST);
  print_r($_POST);
  print_r($_GET);

  echo file_get_contents( 'php://input' );
?>

如果我运行代码,我会得到以下日志记录:
2012-12-19 09:24:09.061 MTG Deck Builder[7921:570f] 0x0,(null) 2012-12-19 09:24:09.062 MTG Deck Builder[7921:570f] 结果:数组 ( ) 数组 ( ) 数组 ( )
如果我直接导航到URL并附加?test1=hello&test2=world(显然使用GET而不是POST),我会得到:
数组 ( [test1] => hello [test2] => world [phpbb3_5e63r_u] => 1 [phpbb3_5e63r_k] => [phpbb3_5e63r_sid] => 7ff37e188aa8e0ab57fae6a52f0d1f7b [__utma] => 86369156.392372889.1349352986.1352901458.1353328580.11 [__utmz] => 86369156.1351935106.8.2.utmcsr=hankinsoft.com|utmccn=(referral)|utmcmd=referral|utmcct=/website/forum/10-mtg-magic-the-gathering-trading-card-game-tcg-da/634-new-forum.html [style_cookie] => null ) 数组 ( ) 数组 ( [test1] => hello [test2] => world )
所以我知道我的PHP正在正确记录get/requests,但我不确定为什么我的objective-c代码的POST无法工作。我相信我正在忽略一些愚蠢的东西。您对我错过了什么有何建议?

2
尝试通过设置内容类型和大小。 - Mohit_Jaiswal
不要只将nil赋值给错误,而是做更多的事情,传递一些NSError实例,这样你就可以知道错误来自哪里。希望这能解决你的问题。 - Mohit_Jaiswal
顺便说一下,你想听听关于RestKit的事吗? - moonwave99
@moonwave99 顺便说一下,尽可能避免使用RestKit。那个框架太庞大了。 - Till
谢谢大家。我已经尝试添加内容类型和内容大小(已更新我的问题的详细信息),但仍然没有成功。此外,我还包括了错误详细信息。未检测到任何错误。 - Kyle
请问有人可以帮我吗?http://stackoverflow.com/questions/16861504/nsurlconnection-with-post-doesnt-work - Aranha Silva
3个回答

3
这是因为NSURLConnection不能正确处理重定向。当您向URL http://magicthegatheringdatabase.com/test.php发送POST请求时,服务器响应301 Moved Permanently并重定向到http://www.magicthegatheringdatabase.com/test.php。而不是向新URL发送相同的请求,NSURLConnection会创建一个新的GET请求并丢弃原始请求的HTTPBody。这种行为是由于HTTP规范禁止未经用户确认的请求除HEADGET之外的自动重定向。将方法更改为GET是错误的,但至少它是一种安全的方法,不会损害HTTP资源。
可以使用两个选项解决此问题:
  1. 您可以简单地将请求的URL更改为http://www.magicthegatheringdatabase.com/test.php

  2. 或者您可以使用代理创建NSURLConnection的实例,并实现connection:willSendRequest:redirectResponse:以正确处理重定向,如回答此问题中所述。即使重定向发生更改,这也可以起作用,但需要编写更多代码以等待响应、创建NSMutableData对象、按字节追加并异步处理所有内容(请参阅Apple Developer Documentation)。然而,异步执行任务总是一个好主意:您可以在需要时取消它们,并且您不会冒着阻塞线程很长时间的风险(当您处于主线程时,任何超过1秒钟的时间都是很长的时间)。


谢谢你的回答和详细解释。我知道我肯定忽略了某些简单的东西,而这正是我需要的。 - Kyle

2
你应该尝试添加以下内容:
[request addValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

1

更改:

 NSString *postString = [NSString stringWithFormat:@"tes1=%@&test2=%@", 
                           [@"hello" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                           [@"world" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

现在添加

  [request setHTTPMethod:@"POST"];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接