11

我正在使用 AFNetworking 框架,需要向服务器提交表单(POST)请求。这是服务器期望的示例:

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

我考虑在 AFHTTPClient 中使用 multipartFormRequestWithMethod,就像在使用 AFNetworking发送多个图像后讨论的那样。但我不知道如何使用“radio”类型的输入值附加表单数据。

4

3 回答 3

24

下面是一个使用 NSURLConnection 发送 POST 参数的例子:

// 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];
于 2012-09-30T13:56:40.593 回答
5

如果您查看使用此表单时浏览器向服务器提交的内容(使用浏览器中的调试面板),您会看到您的 POST 请求数据如下所示:

paperid=6&q77=2&q80=blah

也就是说,所选单选按钮中的值条目用作相应 POST 条目的值,并且您只获得所有单选按钮的一个条目。(与切换按钮相反,您可以在其中获得当前选择的每个按钮的值。)

一旦您了解了 POST 字符串的格式,您应该能够使用ASIFormDataRequest以通常的方式创建请求。

于 2012-09-30T07:05:34.407 回答
2

这是如何使用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];
于 2012-10-01T12:44:19.147 回答