Monday, June 4, 2012

iOS: Making a POST Request

Performing a POST request in iOS is not that straightforward. Some have recommended using libraries such as ASIHTTPRequest, though it's no longer being worked on by the original creator.

Set HTTP Method

Using the NSURLRequest class, the default request type is GET. To change to POST:
  1. You need to first ensure that you are using NSMutableURLRequest, otherwise you can't even change it from GET to POST.
  2. Then set "HTTPMethod" to POST i.e. (urlReq.HTTPMethod = @"POST";)

Encoding POST Parameters

Next, the POST body needs to be created in a few steps. Firstly, the content of each parameter needs to be encoded in the Form-URL encoding format.

NSString provides a method "stringByAddingPercentEscapesUsingEncoding", but it's been reported that it creates output that won't be acceptable to web-servers. The solution is to call the "CFURLCreateStringByAddingPercentEscapes" function.

NSString *encodedString = (__bridge NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (__bridge CFStringRef)sourceString, NULL, (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ", kCFStringEncodingISOLatin1);

Note the "__bridge" is needed if you use ARC.

References for this

Create the name/value pairs, and obtain the NSData format, here's an example for one parameter:

NSString *postBody = [NSString stringWithFormat:@"var1=%@",encodedString];
NSData *postBodyData = [postBody dataUsingEncoding:NSASCIIStringEncoding];
urlRequest.HTTPBody = postBodyData;

Notes

Some examples have also included setting headers such as Content-Length and Content-Type. It worked for me without them, but it could be just with the server I was working with.

References

No comments:

Post a Comment