iPhone sending POST with NSURLConnection

后端 未结 5 1838
萌比男神i
萌比男神i 2020-11-27 14:27

I\'m having some problems with sending POST data to a PHP script with NSURLConnection. This is my code:

    const char *bytes = [[NSString stringWithFormat:@         


        
5条回答
  •  有刺的猬
    2020-11-27 15:28

    Your data is wrong. If you expect the data to be found in the $_POST array of PHP, it should look like this:

    const char *bytes = "mydata=Hello%20World";
    

    If you want to send XML Data, you need to set a different HTTP Content Type. E.g. you might set

    application/xml; charset=utf-8
    

    If you set no HTTP Content Type, the default type

    application/x-www-form-urlencoded
    

    will be used. And this type expects the POST data to have the same format as it would have in a GET request.

    However, if you set a different HTTP Content Type, like application/xml, then this data is not added to the $_POST array in PHP. You will have to read the raw from the input stream.

    Try this:

    NSString * str = [NSString stringWithFormat:@"\n%@", data];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:[str dataUsingEncoding:NSUTF8StringEncoding]];
    

    and on the server try the following PHP:

    $handle = fopen("php://input", "rb");
    $http_raw_post_data = '';
    while (!feof($handle)) {
        $http_raw_post_data .= fread($handle, 8192);
    }
    fclose($handle);
    

    Please note that this only works if the HTTP header of your POST is not application/x-www-form-urlencoded. If it is application/x-www-form-urlencoded then PHP itself reads all the post data, decodes it (splitting it into key/value pairs), and finally adds it to the $_POST array.

提交回复
热议问题