如何在AFNetworking 2.0中执行简单的form-urlencoded POST请求?

时间:2013-11-19 05:39:15

标签: ios networking afnetworking-2

如何在AFNetworking 2.0中复制此NSURLConnection代码?

NSString *post = @"key=xxx";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://test.com/"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[conn start];

3 个答案:

答案 0 :(得分:7)

简答:使用AFNetworking提供的AFHTTPRequestSerializer

根据document

[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];

发送:

POST http://example.com/
Content-Type: application/x-www-form-urlencoded

foo=bar&baz[]=1&baz[]=2&baz[]=3

如果您使用AFHTTPRequestOperationManager

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];

// you can use different serializer for response.
manager.responseSerializer = [AFJSONResponseSerializer serializer]; 

答案 1 :(得分:5)

在AFNetworking页面github link

中给出

发送帖子请求的代码如下,只需在xocde中导入项目中的AFNeworking文件夹并添加必要的框架getting started with afnetworking

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"key": @"xxx"};
[manager POST:@"http://test.com" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

答案 2 :(得分:1)

要使用AFNetworking POST表单数据,您必须使用NSDictionary创建此格式:

说你必须寄这些参数:

{
  key1 = val1;
  key2 = val2;
  key3 = val3;
}

使用UTF8Encoding创建此格式并对数据进行编码:

key1=val1&key2=val2&key3=val3

您可以使用以下格式:

NSMutableString *str = [[NSMutableString alloc]init];
NSArray *allKeys = [dict allKeys];
for (NSString *key in allKeys) {
    [str appendString:key];
    [str appendString:@"="];
    [str appendString:[dict valueForKey:key]];
    [str appendString:@"&"];
}
[str deleteCharactersInRange:NSMakeRange([str length]-1, 1)];
NSData *requestBodyData = [str dataUsingEncoding:NSUTF8StringEncoding];

AFNetworking创建NSMutableRequest。在NSMutableRequest实例的HTTPBody中传递此requestBodyData

完成。