OGeek|极客世界-中国程序员成长平台

标题: iphone - 在 iPhone 中使用 POST 将包含 XML 数据的变量发布到 Web 服务器 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 13:23
标题: iphone - 在 iPhone 中使用 POST 将包含 XML 数据的变量发布到 Web 服务器

我浏览了许多类似主题的未解决问题,但遗憾的是找不到答案。 问题是我是发送 POST/GET 消息的新手,我不确定如何将包含 XML 数据的变量发布到网络服务器。

"在指定的 URL 上使用带有 XML 字符串的 POST 或 GET 变量 "test"。

我知道如何建立连接,并将 XML 放入 HTTPBody 并发出请求。但我不知道如何为变量指定 XML。

请帮忙。



Best Answer-推荐答案


如果“为变量指定 XML”是指将 XML 字符串作为 multipart/form-data 的一部分发送,那么这很容易。

您只需像您一样将您的 XML 字符串附加到您的请求正文中,但另外将其封装在边界之间并添加一个内容 header 。

NSURL *remoteURL = [NSURL URLWithString"http://someurl"];
NSMutableURLRequest *imageRequest = [[NSMutableURLRequest alloc] initWithURL:remoteURL];
//A unique string that will be repeated as a separator
NSString *boundary = @"14737809831466499882746641449";

//this is important so the webserver knows that you're sending multipart/form-data
NSString *contentType = [NSString stringWithFormat"multipart/form-data; boundary=%@", boundary];
[imageRequest addValue:contentType forHTTPHeaderField: @"Content-Type"];

NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; //boundary
[body appendData:[@"Content-Disposition: form-data; name=\"xmlString\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; //your content header
[body appendData:[xmlString dataUsingEncoding:NSUTF8StringEncoding]]; //your content itself
[body appendData:[[NSString stringWithFormat"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[imageRequest setHTTPMethod"OST"]; //set Method as POST
[imageRequest setHTTPBody:body];

NSData *data = [NSURLConnection sendSynchronousRequest:imageRequest returningResponse:nil error:nil];

或者...如果您想将 GET 变量作为查询字符串的一部分发送,只需对其进行 URL 编码并将其添加为 URL 的一部分。

NSString *xmlString = @"<xml>...</xml>";
NSString *escapedString = [xmlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *urlString = [NSString stringWithFormat"http://someserver/?xmlString=%@",escapedString];
NSURL *url = [NSURL URLWithString:urlString];
NSLog(@"Current URL: %@", url);

这是带有 HTTP GET 参数的请求 URL 的样子。

我希望这会有所帮助。

关于iphone - 在 iPhone 中使用 POST 将包含 XML 数据的变量发布到 Web 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18106701/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4