无法使用NSURLConnection获取iOS http帖子

Kyl*_*yle 5 post objective-c nsurlrequest ios

我正在尝试使用POST消息.我已经看过几篇帖子描述了这样做,比如这个,但我仍然无法让它发挥作用.以下是我的目标-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);
Run Code Online (Sandbox Code Playgroud)

这是我的PHP:

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

  echo file_get_contents( 'php://input' );
?>
Run Code Online (Sandbox Code Playgroud)

如果我运行代码,我会得到以下记录:

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] Result: Array
(
)
Array
(
)
Array
(
)

如果我直接导​​航到url并追加?test1=hello&test2=world(显然使用GET而不是POST),我得到:

Array
(
    [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
)
Array
(
)
Array
(
    [test1] => hello
    [test2] => world
)

所以我知道我的PHP正在正确记录get/requests,但我不确定为什么我的POST通过objective-c代码不起作用.我很确定我忽视了一些愚蠢的事情.关于我缺少什么的任何建议?

Nic*_*idt 3

这是因为NSURLConnection没有正确处理重定向。

当您将POST请求发送到 URL时http://magicthegatheringdatabase.com/test.php,服务器会响应301 Moved Permanently并重定向到http://www.magicthegatheringdatabase.com/test.php

不是将相同的请求发送到新的 URL,而是NSURLConnection创建一个新GET请求并丢弃原始请求的HTTPBody. 此行为是由于HTTP 规范禁止在未经用户确认的情况下自动重定向HEAD请求GET。将方法更改为GET是错误的,但至少这是一个安全的方法,不会损害 HTTP 资源。

这个问题可以通过两种选择来解决:

  1. 您只需将请求的 URL 更改为http://www.magicthegatheringdatabase.com/test.php

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