Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simulate HTTP form (POST) submit on iOS

I'm using AFNetworking framework and need to submit a form (POST) request to the server. Here's a sample of what server expects:

<form id="form1" method="post" action="http://www.whereq.com:8079/answer.m">
    <input type="hidden" name="paperid" value="6">
    <input type="radio" name="q77" value="1">
    <input type="radio" name="q77" value="2">
    <input type="text" name="q80">
</form> 

I consider using the multipartFormRequestWithMethod in AFHTTPClient, just like what was discussed in post Sending more than one image with AFNetworking. But I have no idea about how to append the form data with "radio" type input value.

like image 494
Chris Chen Avatar asked Sep 30 '12 04:09

Chris Chen


3 Answers

Here's an example using NSURLConnection to send POST parameters:

// Note that the URL is the "action" URL parameter from the form.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.whereq.com:8079/answer.m"]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
//this is hard coded based on your suggested values, obviously you'd probably need to make this more dynamic based on your application's specific data to send
NSString *postString = @"paperid=6&q77=2&q80=blah";
NSData *data = [postString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
[request setValue:[NSString stringWithFormat:@"%u", [data length]] forHTTPHeaderField:@"Content-Length"];
[NSURLConnection connectionWithRequest:request delegate:self];
like image 77
Andy Obusek Avatar answered Oct 08 '22 11:10

Andy Obusek


If you take a look at what the browser submits to the server when using this form (using the debug panel in your browser) you'd see that your POST request data looks like this:

paperid=6&q77=2&q80=blah

That is the value entry from the selected radio button is used as the value for the corresponding POST entry, and you get just one entry for all of the radio buttons. (As opposed to toggle buttons, where you get a value for each that is currently selected.)

Once you understand the format of the POST string you should be able to create the request in the usual manner using ASIFormDataRequest.

like image 45
Michael Anderson Avatar answered Oct 08 '22 11:10

Michael Anderson


Here is how to do with STHTTPRequest

STHTTPRequest *r = [STHTTPRequest requestWithURLString:@"http://www.whereq.com:8079/answer.m"];

r.POSTDictionary = @{ @"paperid":@"6", @"q77":"1", @"q80":@"hello" };

r.completionBlock = ^(NSDictionary *headers, NSString *body) {
    // ...
};

r.errorBlock = ^(NSError *error) {
    // ...
};

[r startAsynchronous];
like image 2
nst Avatar answered Oct 08 '22 13:10

nst