0

I am sending a POST method from my iOS app. 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?

If yes, what header fields are necessary?

Thanks!

Balázs Vincze
  • 2,903
  • 2
  • 24
  • 52

2 Answers2

0

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.

Arclite
  • 2,491
  • 26
  • 42
-1

From NSMutableURLRequest Class Reference:

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.

a simple POST request might look like this:

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
Community
  • 1
  • 1
forkaj
  • 126
  • 5
  • Thanks! So the content type is not necessary either? What is the default content type? – Balázs Vincze Aug 01 '16 at 08:23
  • @BalázsVincze There seems to be no default content type. But if postData is set, there are two types available: http://stackoverflow.com/questions/4007969/application-x-www-form-urlencoded-or-multipart-form-data – forkaj Aug 01 '16 at 11:41