Question

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.

Was it helpful?

Solution

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];

OTHER TIPS

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.

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];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top