ios 将数据附加到 POST NSURLRequest
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6148900/
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
Append data to a POST NSURLRequest
提问by Tim
How do you append data to an existing POST
NSURLRequest
? I need to add a new parameter userId=2323
.
如何将数据附加到现有的POST
NSURLRequest
?我需要添加一个新参数userId=2323
。
回答by Simon Lee
If you don't wish to use 3rd party classes then the following is how you set the post body...
如果您不想使用 3rd 方类,那么以下是您设置帖子正文的方法...
NSURL *aUrl = [NSURL URLWithString:@"http://www.apple.com/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
NSString *postString = @"company=Locassa&quality=AWESOME!";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request
delegate:self];
Simply append your key/value pair to the post string
只需将您的键/值对附加到帖子字符串
回答by Kevin
All the changes to the NSMutableURLRequest
must be made before calling NSURLConnection
.
NSMutableURLRequest
必须在调用 之前对进行所有更改NSURLConnection
。
I see this problem as I copy and paste the code above and run TCPMon
and see the request is GET
instead of the expected POST
.
当我复制并粘贴上面的代码并运行TCPMon
并看到请求GET
而不是预期的时,我看到了这个问题POST
。
NSURL *aUrl = [NSURL URLWithString:@"http://www.apple.com/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
NSString *postString = @"company=Locassa&quality=AWESOME!";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request
delegate:self];
回答by Rob
The previous posts about forming POST
requests are largely correct (add the parameters to the body, not the URL). But if there is any chance of the input data containing any reserved characters (e.g. spaces, ampersand, plus sign), then you will want to handle these reserved characters. Namely, you should percent-escape the input.
之前关于形成POST
请求的帖子在很大程度上是正确的(将参数添加到正文,而不是 URL)。但是如果输入数据有可能包含任何保留字符(例如空格、与号、加号),那么您将需要处理这些保留字符。也就是说,您应该对输入进行百分比转义。
//create body of the request
NSString *userid = ...
NSString *encodedUserid = [self percentEscapeString:userid];
NSString *postString = [NSString stringWithFormat:@"userid=%@", encodedUserid];
NSData *postBody = [postString dataUsingEncoding:NSUTF8StringEncoding];
//initialize a request from url
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPBody:postBody];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//initialize a connection from request, any way you want to, e.g.
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Where the precentEscapeString
method is defined as follows:
其中precentEscapeString
方法定义如下:
- (NSString *)percentEscapeString:(NSString *)string
{
NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)string,
(CFStringRef)@" ",
(CFStringRef)@":/?@!$&'()*+,;=",
kCFStringEncodingUTF8));
return [result stringByReplacingOccurrencesOfString:@" " withString:@"+"];
}
Note, there was a promising NSString
method, stringByAddingPercentEscapesUsingEncoding
(now deprecated), that does something very similar, but resist the temptation to use that. It handles some characters (e.g. the space character), but not some of the others (e.g. the +
or &
characters).
请注意,有一个有前途的NSString
方法,stringByAddingPercentEscapesUsingEncoding
(现在已废弃),这确实非常类似的东西,但抵制使用的诱惑。它处理一些字符(例如空格字符),但不处理其他一些字符(例如+
或&
字符)。
The contemporary equivalent is stringByAddingPercentEncodingWithAllowedCharacters
, but, again, don't be tempted to use URLQueryAllowedCharacterSet
, as that also allows +
and &
pass unescaped. Those two characters are permitted within the broader "query", but if those characters appear within a value within a query, they must escaped. Technically, you can either use URLQueryAllowedCharacterSet
to build a mutable character set and remove a few of the characters that they've included in there, or build your own character set from scratch.
当代的等价物是stringByAddingPercentEncodingWithAllowedCharacters
,但同样,不要试图使用URLQueryAllowedCharacterSet
,因为这也允许+
并&
通过未转义。这两个字符在更广泛的“查询”中是允许的,但如果这些字符出现在查询的值中,则必须对其进行转义。从技术上讲,您可以使用URLQueryAllowedCharacterSet
来构建可变字符集并删除它们包含在其中的一些字符,或者从头开始构建自己的字符集。
For example, if you look at Alamofire's parameter encoding, they take URLQueryAllowedCharacterSet
and then remove generalDelimitersToEncode
(which includes the characters #
, [
, ]
, and @
, but because of a historical bug in some old web servers, neither ?
nor /
) and subDelimitersToEncode
(i.e. !
, $
, &
, '
, (
, )
, *
, +
, ,
, ;
, and =
). This is correct implementation (though you could debate the removal of ?
and /
), though pretty convoluted. Perhaps CFURLCreateStringByAddingPercentEscapes
is more direct/efficient.
例如,如果您查看 Alamofire 的参数 encoding,它们会采用URLQueryAllowedCharacterSet
然后删除generalDelimitersToEncode
(其中包括字符#
, [
, ]
, and @
,但由于某些旧 Web 服务器中的历史错误,既不是?
也不是/
)和subDelimitersToEncode
(即!
, $
, &
, '
, (
, )
, *
,+
,,
,;
,和=
)。这是正确的实现(尽管您可以讨论删除?
和/
),尽管非常复杂。也许CFURLCreateStringByAddingPercentEscapes
更直接/更有效。
回答by Alex Terente
NSURL *url= [NSURL URLWithString:@"https://www.paypal.com/cgi-bin/webscr"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:@"POST"];
NSString *postString = @"userId=2323";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
回答by David Fulton
The example code above was really helpful to me, however (as has been hinted at above), I think you need to use NSMutableURLRequest
rather than NSURLRequest
. In its current form, I couldn't get it to respond to the setHTTPMethod
call. Changing the type fixed things right up.
上面的示例代码对我很有帮助,但是(正如上面所暗示的那样),我认为您需要使用NSMutableURLRequest
而不是NSURLRequest
. 以目前的形式,我无法让它响应setHTTPMethod
电话。更改类型可以解决问题。
回答by spaceMonkey
Any one looking for a swift solution
任何寻求快速解决方案的人
let url = NSURL(string: "http://www.apple.com/")
let request = NSMutableURLRequest(URL: url!)
request.HTTPBody = "company=Locassa&quality=AWESOME!".dataUsingEncoding(NSUTF8StringEncoding)