我正在尝试使 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 甲板生成器 [7921:570f] 0x0,(空) 2012-12-19 09:24:09.062 MTG Deck Builder[7921:570f] 结果:数组 ( ) 大批 ( ) 大批 ( )
如果我直接导航到 url 并附加?test1=hello&test2=world
(显然使用 GET 而不是 POST),我会得到:
大批 ( [test1] => 你好 [test2] => 世界 [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=(推荐)|utmcmd=推荐|utmcct=/website/forum/10-mtg-magic-the-gathering-trading-card-game-tcg- da/634-new-forum.html [style_cookie] => 空 ) 大批 ( ) 大批 ( [test1] => 你好 [test2] => 世界 )
所以我知道我的 PHP 正在正确记录 get/requests,但我不确定为什么我通过 Objective-c 代码的 POST 不起作用。我很确定我忽略了一些愚蠢的事情。关于我所缺少的任何建议?