iPhone Application button with URL POST method
I would like to ask about the button and the url post method in iPhone application.
In my program, I want the user to click a button, and then a url will be called by POST method. For the url, it may need to redirect to somewhere (302 or 30开发者_JS百科3) etc and final is 200.
I have complete the button and the success page, however, I don't know how to use the objective-C library. I found lots of reference of this forum, but I don't understand what the code means. Can anyone help me?
The following is a question which I believe related to the question. Invoking a http post URL from iphone using .net web service
Thank you very much.
If you're okay with blocking the thread you're making the request on, this is just about as simple as it gets.
NSString *postBody = [NSString stringWithFormat:@"param1=%@¶m2", param1value, param2value];
NSData *postData = [postBody dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:targetURL];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
A few caveats:
- This will perform a synchronous (blocking) request, so either do it on a background thread or look into using the NSURLConnection delegate methods.
- POST data must be URL-encoded, so you may need to do some preprocessing of your parameter values.
- Redirects will occur automatically until a 200 OK or an error is encountered.
精彩评论