How to simulate HTTP form (POST) submit on iOS

2019-02-02 19:40发布

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.

3条回答
贼婆χ
2楼-- · 2019-02-02 20:35

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.

查看更多
小情绪 Triste *
3楼-- · 2019-02-02 20:38

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];
查看更多
Juvenile、少年°
4楼-- · 2019-02-02 20:39

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];
查看更多
登录 后发表回答