如何通过PHP中的iPhone应用程序响应POST?

时间:2011-05-21 20:46:33

标签: php iphone http

我有Objective C代码创建一个NSUrlConnection,如下所示:

//prepar request
    NSString *urlString = [NSString stringWithFormat:@"http://ctruman.info/post.php"];
    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];

    //set headers
    NSString *contentType = [NSString stringWithFormat:@"text/xml"];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

    //create the body
    NSString *formData = [[NSString alloc] initWithFormat:@"%@  %@", username.text, password.text];

    NSData *postData = [[NSString stringWithString:formData] dataUsingEncoding:NSUTF8StringEncoding];

    //post
    [request setHTTPBody:postData];

    //get response
    NSHTTPURLResponse* urlResponse = nil;  
    NSError *error = [[NSError alloc] init];  
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];  
    NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    NSLog(@"Response Code: %d", [urlResponse statusCode]);
    if ([urlResponse statusCode] >= 200 && [urlResponse statusCode] < 300) {
        NSLog(@"Response: %@", result);
     }  

然后我有一个php脚本应该读取我发送的POST变量:

<?php
print('<pre>');
print_r($_POST);
print('</pre>');
?>

当我执行此操作时,NSLog会吐出以下内容:     

Array
    (
    )
为什么不打印我的帖子变量?我是否错误地发出了POST请求?

2 个答案:

答案 0 :(得分:2)

在我看来,PHP正在尝试读取您的POST提交,就好像它是格式正确的PHP POST有效负载一样。相反,您将内容类型设置为XML内容 - 这可能会混淆PHP的内容。它正在寻找编码变量,并寻找XML。

你有两个选择:

  1. 读入XML并使用PHP自行解析: $ xml = file_get_contents('php:// input'); 阅读输入的示例如下:http://www.codediesel.com/php/reading-raw-post-data-in-php/ 然后你可以用PHP的xml支持解析它:http://us.php.net/xml

  2. 重新编码您的目标-C,只需将正常的POST参数发送到服务器即可。我使用ASIHTTPRequest库,这很容易。 http://allseeing-i.com/ASIHTTPRequest/

答案 1 :(得分:1)

以下代码正常运行。

<强>目标C

NSString *name = @"Anne"; // encode this
NSString *pass = @"p4ssw0rd"; // encode this
NSString *requestString = [NSString stringWithFormat:@"&name=%@&pass=%@",name,pass];
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: @"http://localhost/post.php"]]; 
[request setHTTPMethod: @"POST"];
[request setHTTPBody: requestData];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
NSString *resultString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"%@",resultString);

<强> PHP

<?php

print_r($_POST);

?>

<强>结果

Array
(
    [name] => Anne
    [pass] => p4ssw0rd
)

<强>替代

结帐ASIHTTPRequest:
http://allseeing-i.com/ASIHTTPRequest/