2011-05-15 66 views
1

我是相当新的iOS开发,并希望发送一个请求消息到我在PHP中创建的Web服务。它将接受XML请求,处理并提供响应XML消息。iPhone Web服务NSData和PHP

但是,我遇到的问题是,当发送数据到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而不转换为数据,或者有没有办法将NSData字符串转换为PHP服务器端的可读XML?

在此先感谢。

Pazzy

编辑:包括请求代码:

// 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"]; 
+0

你能分享你如何创建在iPhone端请求的代码? – 2011-05-15 20:37:32

+0

将代码添加到编辑部分 – Pazzy 2011-05-15 20:48:43

+0

然后执行以下操作以创建连接... connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]; – Pazzy 2011-05-15 21:47:33

回答

4

发送的HTTP Body的XML和PHP端解析它,你需要设置Content-Typeapplication/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

+0

谢谢...你的代码与我的看法不一样。我已经添加了[request setValue:@“application/xml; charset = ...”];不知道它的Obj-C代码... – Pazzy 2011-05-15 21:10:29

+0

是否成功地在服务器上获取您的请求? – 2011-05-15 21:13:00

+0

不是很确定......我已经设置了脚本以输出发送给它的内容,并允许connectDidFinish在控制台上打印返回的内容。什么都没有被返回。从PHP端,我有两行输出:$ rawPostXML = file_get_contents(“php:// input”); echo $ rawPostXML; – Pazzy 2011-05-15 21:23:55