简体   繁体   English

iOS必要标头上的POST请求

[英]POST request on iOS necessary headers

I am sending a POST method from my iOS app. 我正在从iOS应用程序发送POST方法。 My code is working fine, but I just copy-pasted it. 我的代码工作正常,但我只是将其粘贴粘贴。

NSString *post = @"key1=val1&key2=val2";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"http://www.nowhere.com/sendFormHere.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

My question is: Is it a must to set anything in the HTTP header field? 我的问题是:是否必须在HTTP标头字段中设置任何内容?

If yes, what header fields are necessary? 如果是,则需要哪些标题字段?

Thanks! 谢谢!

Which header fields are necessary will be determined by the server you are sending the request to. 哪些标头字段是必需的,将由您向其发送请求的服务器确定。 NSURLSession and friends will happily submit any headers you want, or no headers at all. NSURLSession和朋友将很乐意提交您想要的任何标题,或者根本不提交任何标题。

From NSMutableURLRequest Class Reference: 从NSMutableURLRequest类参考:

If the length of your upload body data can be determined automatically (for example, if you provide the body content with an NSData object), then the value of Content-Length is set for you. 如果可以自动确定上载正文数据的长度(例如,如果为正文内容提供一个NSData对象),则将为您设置Content-Length的值。

a simple POST request might look like this: 一个简单的POST请求可能看起来像这样:

NSURL *url = [NSURL URLWithString:@"http://www.nowhere.com/sendFormHere.php"];
NSData *postData = [@"key1=val1&key2=val2" dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:@"POST"]; //The default HTTP method is “GET”.
[request setHTTPBody:postData]; //query string is sent in the HTTPBody of a POST request

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM