douzhuo5671 2011-05-21 20:46
浏览 24
已采纳

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

I have Objective C code creating an NSUrlConnection as follows:

//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);
     }  

Then I have a php script that is supposed to read my POST variables that are being sent:

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

When I execute this, NSLog spits out the following:

Array
    (
    )
Why is it not printing out my post variables? Am I making the POST request incorrectly?
  • 写回答

2条回答 默认 最新

  • doutao5499 2011-05-21 21:51
    关注

    As it looks to me, PHP is trying to read your POST submission as if it were a properly formatted PHP POST payload. Instead, you're setting the content-type to XML content -- which probably confuses the heck out of PHP. It's looking for encoded variables, and finding XML.

    You've got 2 options:

    1. Read in the XML and parse it yourself using PHP: $xml = file_get_contents('php://input'); an example for reading input is here: http://www.codediesel.com/php/reading-raw-post-data-in-php/ then you can parse it with PHP's xml support: http://us.php.net/xml

    2. Recode your objective-C to just send normal POST parameters up to the server. I use the ASIHTTPRequest libraries and it's easy. http://allseeing-i.com/ASIHTTPRequest/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?