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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 23:29:36  来源:igfitidea点击:

POST request in Objective-C

objective-cxcodepostrequest

提问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=value2form). 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:

你不得不: