gpt4 book ai didi

php - iPhone Web服务NSData和PHP

转载 作者:行者123 更新时间:2023-12-01 18:33:04 25 4
gpt4 key购买 nike

我是iOS开发的新手,想向我用PHP创建的Web服务发送请求消息。它将接受XML请求,进行处理,然后提供响应XML消息。

但是,我遇到的问题是,当将数据发送到Webservice时,它是NSData形式的。

NSLog发送的数据为:

<3c3f786d 6c207665 7273696f etc etc ... 743e>

但是,PHP脚本期望这样的XML消息:
<?xml version="1.0" ?><request-message><tag-1></tag-1><tag-2></tag-2></request-message>

所以我的问题是,有没有办法在不转换为数据的情况下发送XML,还是有办法将NSData字符串转换为PHP服务器端的可读XML?

提前致谢。

扎眼

编辑:要包括请求代码:
// Construct the webservice URL
NSURL *url = [NSURL URLWithString:@"http://localhost/web/check_data.php"];

NSString *requestXML = @"<?xml version='1.0'?><request-message><tag-1>VALUE1</tag-1><tag-2>VALUE2</tag-2></request-message>";

NSData *data = [requestXML dataUsingEncoding:NSUTF8StringEncoding];

// Create a request object with that URL
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];

[request setHTTPBody:data];
[request setHTTPMethod:@"POST"];

最佳答案

HTTP Body上发送XML并在PHP端进行解析,您需要将Content-Type设置为application/xml; charset=utf-8:

NSString* sXMLToPost = @"<?xml version=\"1.0\" ?><request-message><tag-1></tag-1><tag-2></tag-2></request-message>";

NSData* data = [sXMLToPost dataUsingEncoding:NSUTF8StringEncoding];

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

[request setHTTPMethod:@"POST"];
[request setValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:[sXMLToPost dataUsingEncoding:NSUTF8StringEncoding]];

NSURLResponse *response;
NSError *error;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

if (error) {..handle the error}

并在服务器上尝试以下PHP代码:
$handle = fopen("php://input", "rb");
$http_raw_post_data = '';
while (!feof($handle)) {
$http_raw_post_data .= fread($handle, 8192);
}
fclose($handle);

看看这个 iPhone sending POST with NSURLConnection

关于php - iPhone Web服务NSData和PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6011033/

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