Post Request with AFHttpRequestOperationManager not working - ios7

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.

Related

Image upload using AFMultipartFormData AFNetworking 3.0

NSURL *URL = [NSURL URLWithString:#"some APi"];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
UIImage *myImageObj = [UIImage imageNamed:#"avatar.jpg"];
NSData *imageData= UIImagePNGRepresentation(myImageObj);
[manager POST:URL.absoluteString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData
name:#"file"
fileName:#"avatar.jpg" mimeType:#"image/jpeg"];
// etc.
} progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"Response: %#", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"Error: %#", error);
}];
I am trying to upload image using afnetworking 3.0 but getting this error every time
Domain=com.alamofire.error.serialization.response Code=-1011 "Request
failed: internal server error (500)"
UserInfo={com.alamofire.serialization.response.error.response= { URL: Some URL } { status
code: 500, headers {
"Access-Control-Allow-Origin" = "*";
"Content-Length" = 291;
"Content-Type" = "text/html";
Date = "Thu, 26 Jan 2017 11:41:19 GMT";
Server = "Werkzeug/0.11.11 Python/2.7.12"; } },
luckily postman provide objective-C and some other languages code but with AFNetworking i used this
NSURL *URL = [NSURL URLWithString:#"your URL"];
UIImage *myImageObj = [UIImage imageNamed:#"image.jpg"];
NSData *imageData= UIImageJPEGRepresentation(myImageObj, 0.6);
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//manager.responseSerializer=[AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager.requestSerializer setValue:#"multipart/form-data" forHTTPHeaderField:#"Content-Type"];
[manager POST:URL.absoluteString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData
name:#"file"
fileName:#"image.jpg" mimeType:#"image/jpeg"];
// etc.
} progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"Response: %#", responseObject);
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"%#",string);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"Error: %#", error);
}];

AFNetworking 2 - Image upload - Request failed: unsupported media type (415)

I know this question was answered multiple times, but I tried all the answers with no luck. I don't think that I do something fundamentally wrong but something goes definitely wrong here.
I use the following code to upload PNG files to tinypng.com. As far as I can see the upload itself works, but I receive the error message: Request failed: unsupported media type (415)
The images I use are loaded as JPEG, then resized and transformed to PNG format. The saved files are fine. Now I want send them to the TinyPNG API before I save them to disc.
If anyone has an idea whats wrong or has experience with that service, please let me know.
Thanks in advance!
Detailed error message
Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: unsupported media type (415)"
UserInfo=0x6000000e4900 {
com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x600000220200> { URL: https://api.tinypng.com/shrink }
{
status code: 415, headers {
Connection = "keep-alive";
"Content-Length" = 77;
"Content-Type" = "application/json; charset=utf-8";
Date = "Tue, 16 Dec 2014 20:24:16 GMT";
Server = "Apache/2";
"Strict-Transport-Security" = "max-age=31536000";
"X-Powered-By" = "Voormedia (voormedia.com/jobs)";
}
},
NSErrorFailingURLKey=https://api.tinypng.com/shrink,
com.alamofire.serialization.response.error.data=<7b226572 726f7222 3a224261 64536967 6e617475
7265222c 226d6573 73616765 223a2244 6f657320 6e6f7420 61707065 61722074 6f206265 20612050
4e47206f 72204a50 45472066 696c6522 7d>,
NSLocalizedDescription=Request failed: unsupported media type (415)
}
The code I use
-(void) uploadImage:(NSImage *)image {
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:TINY_PNG_URL]];
CGImageRef cgRef = [image CGImageForProposedRect:NULL
context:nil
hints:nil];
NSBitmapImageRep *newRep = [[NSBitmapImageRep alloc] initWithCGImage:cgRef];
[newRep setSize:[image size]]; // if you want the same resolution
NSData *imageData = [newRep representationUsingType:NSPNGFileType properties:nil];
NSDictionary *parameters = #{#"username": USERNAME, #"password" : PASSWORD};
AFHTTPRequestOperation *operation = [manager POST:#"" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//append image
[formData appendPartWithFileData:imageData
name:#"filename"
fileName:#"photo.png"
mimeType:#"image/png"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %# ***** %#", operation.responseString, responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %# ***** %#", operation.responseString, error);
}];
[operation start];
}
With the support of Mattijs from TinyPNG I've got it working! Thanks Mattijs!
The problem was, that the TinyPNG API expects the request body to only be the image data, which isn't the case with the multipart form data body I used in my original code.
My working solution is:
-(void) uploadImage:(NSImage *)image {
NSData *imageData = [self PNGRepresentationOfImage:image];
NSURL *url = [NSURL URLWithString:TINY_PNG_URL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:imageData];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"image/png" forHTTPHeaderField:#"Content-Type"];
NSString *authStr = [NSString stringWithFormat:#"%#:%#", USERNAME, PASSWORD];
NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id result) {
NSLog(#"Success: %# ***** %#", operation.responseString, result);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %# ***** %#", operation.responseString, error);
}];
[operation start];
}

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]);

AFNetworking 2.0 POST request not working

I am trying to make a POST request using AFNetworking 2.0.
This is the code
NSMutableDictionary *params=[NSMutableDictionary dictionary];
[params setValue:#"iOS" forKey:#"device"];
[params setValue:#"" forKey:#"token"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:ServerURL parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"%#",responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#",error);
}];
I have followed many question and they all have done something similar to what i have done above . I do not understand what i am missing. i get a valid response using the old Afnetworking library.
The error i get is
{ status code: 200, headers {
Connection = close;
"Content-Length" = 195;
"Content-Type" = "text/html; charset=UTF-8";
Date = "Mon, 21 Apr 2014 06:53:55 GMT";
Server = "Apache/2.2.25 (Amazon)";
"X-Powered-By" = "PHP/5.3.27";
} }, NSLocalizedDescription=Request failed: unacceptable content-type: text/html}
I resolved it by adding
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
not sure if this is the right way , but it worked for me
Cheers.

How to change AFNetworking2.0 parameter encoding?

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.