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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 20:06:41  来源:igfitidea点击:

Append data to a POST NSURLRequest

iosobjective-cnsurlrequest

提问by Tim

How do you append data to an existing POSTNSURLRequest? I need to add a new parameter userId=2323.

如何将数据附加到现有的POSTNSURLRequest?我需要添加一个新参数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 NSMutableURLRequestmust be made before calling NSURLConnection.

NSMutableURLRequest必须在调用 之前对进行所有更改NSURLConnection

I see this problem as I copy and paste the code above and run TCPMonand see the request is GETinstead 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 POSTrequests 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 precentEscapeStringmethod 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 NSStringmethod, 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 URLQueryAllowedCharacterSetto 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 URLQueryAllowedCharacterSetand 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 CFURLCreateStringByAddingPercentEscapesis 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 NSMutableURLRequestrather than NSURLRequest. In its current form, I couldn't get it to respond to the setHTTPMethodcall. 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)