POST with NSURLConnection - NO JSON

雨燕双飞 提交于 2019-12-03 05:04:06

Here's how to create an ordinary post.

First create a request of the right type:

NSURL *URL = [NSURL URLWithString:@"http://example.com/somepath"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
request.HTTPMethod = @"POST";

Now format your post data as a URL-encoded string, like this:

NSString *params = @"param1=value1&param2=value2&etc...";

Remember to encode the individual parameters using percent encoding. You can't entirely rely on the NSString stringByAddingPercentEscapesUsingEncoding method for this (google to find out why) but it's a good start.

Now we add the post data to your request:

NSData *data = [params dataUsingEncoding:NSUTF8StringEncoding];
[request addValue:@"8bit" forHTTPHeaderField:@"Content-Transfer-Encoding"];
[request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request addValue:[NSString stringWithFormat:@"%i", [data length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:data];

And that's it, now just send your request as normal using NSURLConnection (or whatever).

To interpret the response that comes back, see Maudicus's answer.

You can use the following NSURLConnection method if you target ios 2.0 - 4.3 (It seems to be deprecated in ios 5)

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
  NSString * string = [[NSString alloc] initWithData:data encoding:
                       NSASCIIStringEncoding];

  if (string.intValue == 1) {

  } else {

  }
}
Todd

I've a very similar situation to whitebreadb. I'm not disagreeing with the answers submitted and accepted but would like to post my own as the code provided here didn't work for me (my PHP script reported the submitted parameter as a zero-length string) but I did find this question that helped.

I used this to perform a posting to my PHP script:

NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.myphpscriptlocation.net/index.php?userID=%@",self.userID_field.stringValue]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
request.HTTPMethod = @"POST";
NSURLConnection *c = [NSURLConnection connectionWithRequest:request delegate:self];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!