首页 > 代码库 > AFNetworking2.0参数默认编码格式是UTF8,如何指定参数编码格式为gb2312

AFNetworking2.0参数默认编码格式是UTF8,如何指定参数编码格式为gb2312

问:

AFNetworking2.0 encodes parameters with UTF8. How can I change AFNetworking 2.0‘s parameter encoding to gb2312?

NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding (kCFStringEncodingGB_18030_2000); 

That encoding is gb2312, but how to add it to AFNetworking?

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
NSDictionary *parameters = @{@"__VIEWSTATE":@"dDwtMTg3MTM5OTI5MTs7PkDQD2kYQWAxp4gTWKdd1YunUJ%2B%2B",@"TextBox1": self.xueHao.text,@"TextBox2":self.miMa.text,@"TextBox3":self.yanZhengMa.text,@"RadioButtonList1":@"%D1%A7%C9%FA"};
[manager POST:@"http://172.21.96.64/default2.aspx" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);//提交表单

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", @"???");
}];  }


 

Response Headers
Cache-Control:no-cache, no-store
Content-Length:5628
Content-Type:text/html; charset=gb2312
Date:Sun, 16 Feb 2014 14:00:14 GMT
Expires:-1
Pragma:no-cache
Pragma:no-cache
Server:Microsoft-IIS/6.0
X-AspNet-Version:1.1.4322
X-Powered-By:ASP.NET


答:

After digging around in the source code, it looks like AFHTTPRequestOperationManager has a property for the request serializer - which then has a property for the string encoding.

So, you should be able to do this:

NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding (kCFStringEncodingGB_18030_2000);

RequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
manager.requestSerializer.stringEncoding = enc;
NSDictionary *parameters = @{@"__VIEWSTATE":@"dDwtMTg3MTM5OTI5MTs7PkDQD2kYQWAxp4gTWKdd1YunUJ%2B%2B",@"TextBox1": self.xueHao.text,@"TextBox2":self.miMa.text,@"TextBox3":self.yanZhengMa.text,@"RadioButtonList1":@"%D1%A7%C9%FA"};
[manager POST:@"http://172.21.96.64/default2.aspx" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);//提交表单

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", @"???");
}];  }

Note that I haven‘t had a chance to test this yet, but from looking at the source code I‘m pretty sure it will work. Confirmation would be appreciated.


AFNetworking2.0参数默认编码格式是UTF8,如何指定参数编码格式为gb2312