How to change AFNetworking2.0 parameter encoding? - objective-c

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.

Related

Get plain response from AFNetworking 2.4.1

I'm sending a POST request:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSDictionary *parameters = #{#"method": #"login", #"email":#"email", #"password":#"password"};
[manager POST:#"http://www.apiwebsite.com" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
My responseObject is:
JSON: <0d0a7b22 72657370 6f6e7365 223a224f 4b222c22 30223a22 6d61696c
696e675f 6b657922 2c223122 3a226239 65653766 34643238 64333730
30666663 37393734 65376665 66626663 3136227d>
But calling the api with POSTMAN i get:
{"response":"OK", "id":"1234223123"}
How can I get the plain or JSON response to work with it?
thanks!
To get JSON object use proper serializer AFJSONResponseSerializer instead of AFHTTPResponseSerializer you uses now.
For debug purpose convert NSData to NSString
NSLog(#"JSON: %#", [[NSString alloc] initWithData: responseObject encoding:NSUTF8StringEncoding]);

What is the simplest way to use multipart/form-data in AFNetworking 2.0? ios7

I need to send all my forms on server, firstly text forms and then images. Do someone working with it?
The documentation page of AFNetworking shows the following example:
Multi-Part Request
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"foo": #"bar"};
NSURL *filePath = [NSURL fileURLWithPath:#"file://path/to/image.png"];
[manager POST:#"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:filePath name:#"image" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];

Trying to read html page from a web site using AFNetworking 2.0

I'm trying to have my app load an HTML web page into a "responseObject" that I can later parse.
Here is my code:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/xhtml+xml"];
NSDictionary *parameters = #{#"ghinno": #"1151213"};
[manager GET:#"http://m.ghin.com/HLR.aspx" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"HTTP: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
...and this is the output. I should be seeing the html from the webpage. Can you help me understand what I am doing wrong?
Ah, the answer lies below...
Essentially, it was an encoding / decoding of the response object that was causing my issues. Here is the final solution: (notice the line beginning with "NSString)...
NSURL *URL = [NSURL URLWithString:#"http://m.ghin.com/HLR.aspx?ghinno=1151213"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"%#", string);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
[op start];

Can't get HTML code AFNetworking 2.0

I tried to make GET HTTP response. I need to get the html code for the subsequent parsing, but responseObject is nil.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager GET:#"http://www.example.com/" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError *error;
HTMLParser *parser = [[HTMLParser alloc] initWithString:responseObject error:&error];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
For get html code we will need to build a custom response serializer to decode the NSData response from the web server into a NSString. We will need to subclass AFHTTPResponseSerializer and implement the following method:
- (id)responseObjectForResponse:(NSURLResponse *)response
data:(NSData *)data
error:(NSError *__autoreleasing *)error
{
return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
}
Why for example you have not use this solution below instead of subcalssing. It does the same thing, but you don't need to create additional files, just for overload one method.
So you can just add encoding your responseObjet in the block for example, and it will work as well. I am using POST in my example but it should work with GET in the same way but without parameters, but idea of the just conversation.
+ (void)makeRequestWithParams:(NSDictionary *)params
success:(OperationCompletionBlock)success
failure:(OperationCompletionBlock)failure
{
NSString *path = #"http://www.example.com/";
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFCompoundResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager POST:path parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString* encodedString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"%#", encodedString);
success(nil);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
failure(nil);
}];
}

Post Request with AFHttpRequestOperationManager not working

I am using AFHTTPRequestOperationManager to post some JSON to my server, my code is below.
NSDictionary *parameters = [[NSDictionary alloc] initWithObjectsAndKeys:#"john", #"name", #"xxxxx#gmail.com", #"email", #"xxxx", #"password", #"1", #"type", nil];
// Do any additional setup after loading the view.
AFSecurityPolicy *policy = [[AFSecurityPolicy alloc] init];
[policy setAllowInvalidCertificates:YES];
AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
[operationManager setSecurityPolicy:policy];
[operationManager POST:#"posturl here" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", [responseObject description]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", [error description]);
}];
and the response is as follows:
2013-11-18 16:49:29.780 SwapOnceApiTester[12651:60b] Error: Error Domain=AFNetworkingErrorDomain Code=-1011 "Request failed: unsupported media type (415), got 1664256" UserInfo=0x1565a6c0 {NSErrorFailingURLKey=xxxxxxx, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0x15656db0> { URL: xxxxxxxxx } { status code: 415, headers {
"Cache-Control" = "max-age=604800";
Connection = "keep-alive";
"Content-Type" = "application/json";
Date = "Mon, 18 Nov 2013 11:49:28 GMT";
Expires = "Mon, 25 Nov 2013 11:49:28 GMT";
Server = nginx;
"Transfer-Encoding" = Identity;
"X-Powered-By" = PleskLin;
} }, NSLocalizedDescription=Request failed: unsupported media type (415), got 1664256}
I dont know what the problem is with this.
You need to set your request and response serializers to handle JSON using AFJSONRequestSerializer and AFJSONResponseSerializer before executing your request. Using an NSDictionary literal for your parameters helps code clarity as well:
AFSecurityPolicy *policy = [[AFSecurityPolicy alloc] init];
[policy setAllowInvalidCertificates:YES];
AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
[operationManager setSecurityPolicy:policy];
operationManager.requestSerializer = [AFJSONRequestSerializer serializer];
operationManager.responseSerializer = [AFJSONResponseSerializer serializer];
[operationManager POST:#"posturl here"
parameters: #{#"name": #"john",
#"email": #"xxxxx#gmail.com",
#"password: #"xxxxx",
#"type": #"1"}
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", [responseObject description]);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", [error description]);
}
];
Just solve my problem, my server was not configured to accept the charset utf8 with application/json so i just removed the charset utf for ajson serializer in Afnetworking 2.0 and now it is working correclty.