【问题标题】:iPhone Web Service NSData and PHPiPhone Web 服务 NSData 和 PHP
【发布时间】:2011-08-26 01:04:36
【问题描述】:

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

但是,我遇到的问题是,当向 Web 服务发送数据时,它是 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,或者有没有办法在 PHP 服务器端将 NSData 字符串转换为可读的 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"];

【问题讨论】:

  • 你能分享一下你是如何在 iPhone 端创建请求的代码吗?
  • 在编辑部分添加代码
  • 然后进行以下操作来建立连接... connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];

标签: php iphone xml web-services ios


【解决方案1】:

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

【讨论】:

  • 谢谢...您的代码与我的看起来并没有太大不同。我添加了 [request setValue:@"application/xml; charset=..."];不确定它是否是 Obj-C 代码...
  • 服务器上的请求是否成功?
  • 不完全确定...我已将脚本设置为现在输出发送给它的内容,并允许 connectDidFinish 将返回的内容打印到控制台。没有任何东西被退回。在 PHP 方面,我有两行输出: $rawPostXML = file_get_contents("php://input");回声 $rawPostXML;
  • connectDidFinish?你为什么用那个?你确定你使用的是NSURLConnection sendSynchronousRequest:
猜你喜欢
  • 1970-01-01
  • 2010-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-21
  • 1970-01-01
相关资源
最近更新 更多