xcode Objective-C 中的 POST 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9519054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
POST request in Objective-C
提问by aur0n
Searching the web for some method to send POST requests in Objective-C, I came up with some solutions.
在网上搜索一些在 Objective-C 中发送 POST 请求的方法,我想出了一些解决方案。
That's what I've got:
这就是我所拥有的:
responseData = [NSMutableData new];
NSURL *url = [NSURL URLWithString:@"http://mydomain.com/page.php?"];
NSString *myParameters = [[NSString alloc] initWithFormat:@"str=hello"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[myParameters dataUsingEncoding:NSUTF8StringEncoding]];
The response I receive is an error, because the POST variable "str" hasn't been set.
我收到的响应是一个错误,因为尚未设置 POST 变量“str”。
What am I doing wrong?
我究竟做错了什么?
采纳答案by Tim Dean
It looks like your parameters are intended to be URL parameters (typically in name1=value1&name2=value2
form). You usually don't want to put them in the HTTP body like you are currently doing. Instead, append them to your URL:
看起来您的参数旨在成为 URL 参数(通常是name1=value1&name2=value2
表单)。您通常不想像当前那样将它们放入 HTTP 正文中。相反,将它们附加到您的 URL:
NSString *requestStr = @"hello";
NSString urlString = [NSString stringWithFormat:@"http://mydomain.com/page.php?str=%@", requestStr];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest doesn't provide a more generic way to do this, although you can look at this SO question and its answersfor ideas on how many people deal with this kind of requirement. There are also free and/or open source libraries out there that aim to make this kind of request easier to code.
NSURLRequest 没有提供更通用的方法来做到这一点,尽管您可以查看这个 SO question 及其答案,了解有多少人处理这种需求。还有一些免费和/或开源库旨在使这种请求更容易编码。
回答by Dirk
You will have to:
你不得不:
- set the content type header of the request ("application/x-www-form-urlencoded"). You can set the header by using the
setValue:forHTTPHeaderField:
method of anNSMutableURLRequest
instance. - make sure, that the body actually isactually "Form URL encoded". The example you give looks good, but if you add other parameters, or parameter values containing special characters, make sure, that these are properly encoded. See
CFURLCreateStringByAddingPercentEscapes
.
- 设置请求的内容类型标头(“application/x-www-form-urlencoded”)。您可以使用实例的
setValue:forHTTPHeaderField:
方法设置标题NSMutableURLRequest
。 - 确保正文实际上是“表单 URL 编码”。您提供的示例看起来不错,但如果您添加其他参数或包含特殊字符的参数值,请确保这些参数已正确编码。见
CFURLCreateStringByAddingPercentEscapes
。