gpt4 book ai didi

iPhone 使用 NSURLConnection 发送 POST

转载 作者:行者123 更新时间:2023-12-03 18:19:09 25 4
gpt4 key购买 nike

我在使用 NSURLConnection 将 POST 数据发送到 PHP 脚本时遇到一些问题。这是我的代码:

    const char *bytes = [[NSString stringWithFormat:@"<?xml version=\"1.0\"?>\n<mydata>%@</mydata>", data] UTF8String];

NSURL *url = [NSURL URLWithString:@"http://myurl.com/script.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

[request setHTTPMethod:@"POST"];
[request setHTTPBody:[NSData dataWithBytes:bytes length:strlen(bytes)]];

NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(@"responseData: %@", responseData);

我的 script.php 就这么简单:

<?php
echo $_POST['mydata'];
?>

这在过去对我有用,但由于某种原因,我从 NSLog(@"responseData: %@", responseData); 得到的输出现在只是“<>”而不是“theData”。

可能是某个地方出现了一些蹩脚的错误,但我似乎找不到它?有什么想法吗?

最佳答案

您的数据有误。如果您希望在 PHP 的 $_POST 数组中找到数据,它应该如下所示:

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

如果您想发送 XML 数据,您需要设置不同的 HTTP 内容类型。例如。你可以设置

application/xml; charset=utf-8

如果您未设置 HTTP Content Type,则使用默认类型

application/x-www-form-urlencoded
将使用

。此类型期望 POST 数据具有与 GET 请求中相同的格式。

但是,如果您设置不同的 HTTP 内容类型(例如 application/xml),则该数据不会添加到 PHP 中的 $_POST 数组中。您必须从输入流中读取原始数据。

试试这个:

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

并在服务器上尝试以下 PHP:

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

请注意,只有当您的 POST 的 HTTP header 不是 application/x-www-form-urlencoded 时,这才有效。如果是 application/x-www-form-urlencoded 那么 PHP 本身会读取所有的 post 数据,对其进行解码(将其拆分为键/值对),最后将其添加到 $_POST 数组中。

关于iPhone 使用 NSURLConnection 发送 POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2071788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com