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 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端