Set HTTP Method
Using the NSURLRequest class, the default request type is GET. To change to POST:- You need to first ensure that you are using NSMutableURLRequest, otherwise you can't even change it from GET to POST.
- 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
- https://developer.apple.com/library/mac/#documentation/CoreFOundation/Reference/CFURLRef/Reference/reference.html
- http://cybersam.com/ios-dev/proper-url-percent-encoding-in-ios
- http://madebymany.com/blog/url-encoding-an-nsstring-on-ios
Preparing the POST Body
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.
No comments:
Post a Comment