How do I send a POST request with AFNetworking 2.0 with all the parameters in the URL like such:
http://www.myserver.com?api_key=something&lat=2.4&radius=100
Right now I have:
NSString* query = #"http://example.com?name=param&date=param";
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{};
[manager POST:query parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
But it's not working, I get this error back:
Error Domain=AFNetworkingErrorDomain Code=-1011 "Request failed: bad request (400)
The previous best answer was to get the backend to change and accepts parameters in the body. Thats the preferred method but sometimes some of us are stuck using backends that can't change so I offer this solution....
In the class AFURLRequestSerialization there is a property called HTTPMethodsEncodingParametersInURI and that is an NSSet that contains the http methods that are allowed to use params in the uri GET, HEAD, and DELETE by default.
You could override that and include POST as well.
in AFURLRequestSerialization.m lines 462 has an if statement that checks self.HTTPMethodsEncodingParametersInURI property contains POST. if it doesn't (as it doesn't by default), it will put the parameters in the body.
You can comment out that id statement for a quick test.
To get it to work I recommend overwriting the HTTPMethodsEncodingParametersInURI property.
when setting up your AFHTTPSessionManager it should look like this...
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:self.httpBaseUrl]];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.requestSerializer.HTTPMethodsEncodingParametersInURI = [NSSet setWithArray:#[#"POST", #"GET", #"HEAD", whatever other http methods you need here....]];
this should allow for sending a parameters in the uri of a POST. worked for me, hope it helps someone else
#import "AFNetworking.h"
...
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = #{#"param1": value1,
#"param2": value};
manager.responseSerializer = [AFJSONResponseSerializer serializer]; // if response JSON format
[manager POST:#"http://domain.com/backend.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"%#", responseObject);
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#", error);
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}];
try this
I've had the same problem with you.
Other people's answers seem to be accurate.
The cause of the error is:
when you init NSUrl with parameters such as http:www.baidu.com/api?id=1&name=我,it needs you to encode your urlString with utf-8
such as :
//解决奇葩需求:请求方式为post时,url带?id=1之类。主要原因是url带中文的时候url初始化失败
URLString = [URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError];
Hope to help you!
can you try this.
NSString* apiURL = #"http://example.com"
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:apiURL]];
manager.responseSerializer = [AFJSONResponseSerializer serilizer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/json"];
NSDictionary *parameters = #{#"name":#"John",#"date":"27/12/2013"};
AFHTTPRequestOperation *apiRequest = [manager POST:#"" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog#"response ---%#,responseObject";
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
[apiRequest start];
I was able to do this by creating the string like this:
NSString *relativeURL =[NSString
stringWithFormat:#"/reward/commit?deviceUUID=%#&rewardID=%#",[[Client
sharedInstance] deviceUUID],self.rewardID];
and then passing it as the query. I had to set the requestSerializer and responseSerializer as follows:
client.requestSerializer = [AFJSONRequestSerializer serializer];
client.responseSerializer = [AFHTTPResponseSerializer serializer];
Worked for me once I left the manager.requestSerializer property alone and let it be the default (AFHTTPRequestSerializer).
The service i was POSTing to, was seemingly expecting UTF8 encoded body parameters.
Related
There are other questions with similar titles but none of them helped me. I've to send a PUT request to server in order to change the status of appointment so I've made this method -(void)appointmentStatusChangedTo:(NSString *)statusID atAppointmentID:(NSString *)appointmentID In which I'm setting the URL and Parameters as
NSString *string = [NSString stringWithFormat:#"%#/API/Appointments/3",BaseURLString];
NSDictionary *para = #{
#"AppointmentStatusId":statusID,
#"ID":appointmentID
};
Then I've made URL request as
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:#"PUT" URLString:string parameters:para error:nil];
After that I'm setting the header for an authorization token as
NSString *token = [NSString stringWithFormat:#"Bearer %#",[[NSUserDefaults standardUserDefaults] objectForKey:#"userToken"]];
[req setValue:token forHTTPHeaderField:#"Authorization"];
So finally I'm calling it as
[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error){
if (!error) {
if (response) {
NSLog(#"Respose Object: %#",responseObject);
[self.patientsAppointmentsTableView reloadData];
}
}
else {
// NSLog(#"Error: %#, %#, %#", error, response, responseObject);
NSLog(#"Error: %#", error.localizedDescription);
}
}] resume];
Now it is successfully sending the data to the server but as a response I'm getting
Error: The data couldn’t be read because it isn’t in the correct
format.
I am not sure what the response might look like at the moment as I'm not in contact with backend guy. But as far as I remember it was just a simple 1. SO kindly tell me how to handle any type of response using AFNetworking 3.0 or any change in my code.
try to use below code:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
[serializer setStringEncoding:NSUTF8StringEncoding];
manager.requestSerializer=serializer;
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
Try following code using Afnetworking 3.0
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager GET:url parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"%#",responseObject);
self.responseHandlers(YES,responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
self.responseHandlers(NO,nil);
}];
NSDictionary *parameters = #{
#"project_name": #"hasanProj",
#"project_desc" : #"testing...",
#"project_date" : #"2015-2-22"
};
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithBaseURL:[NSURL URLWithString:#"http://serverIP"]];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:[HRUser sharedUser].userApiKey forHTTPHeaderField:#"Authorization"];
[manager POST:#"/rest/v1/project" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"%#",responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"error: %#",error.localizedDescription);
}];
This code is returning Request failed: bad request (400).
I checked parameter, url they are all correct. I called it from chrome extension postman and getting correct result.
And other requests are working perfectly, even get is working fine.
But why I am getting Request failed: bad request (400) on this?
I was also facing the same error and this worked for me..
manager.responseSerializer.acceptableStatusCodes = [NSIndexSet indexSetWithIndex:400];
or
You can directly parse the response object.
i think there will be problem with the request. your putting wrong type or wrong data.
acceptableContentTypes for request also matters.
second thing the parameters that your sending data to it. check tags correct are not
ask WEB service developer exact need of API.
Code:
NSDictionary *parameters = #{
#"project_name": #"hasanProj",
#"project_desc" : #"testing...",
#"project_date" : #"2015-2-22"
};
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]init];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager.requestSerializer setValue:[HRUser sharedUser].userApiKey forHTTPHeaderField:#"Authorization"];
[manager.requestSerializer.acceptableContentTypes setByAddingObject:#"application/json"];
[manager.responseSerializer.acceptableContentTypes setByAddingObject:#"application/json"];
[manager POST:#"http://serverIP/rest/v1/project" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject)
{
NSLog(#"%#",responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"error: %#",error.localizedDescription);
}];
I'm trying out the new version 2.0 of AFNetworking and I'm getting the error above. Any idea why this is happening? Here's my code:
NSURL *URL = [NSURL URLWithString:kJSONlink];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
[[NSOperationQueue mainQueue] addOperation:op];
I'm using Xcode 5.0.
Also, here's the error message:
Error: Error Domain=AFNetworkingErrorDomain Code=-1016 "Request failed: unacceptable content-type: text/html" UserInfo=0xda2e670 {NSErrorFailingURLKey=kJSONlink, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0xda35180> { URL: kJSONlink } { status code: 200, headers {
Connection = "Keep-Alive";
"Content-Encoding" = gzip;
"Content-Length" = 2898;
"Content-Type" = "text/html";
Date = "Tue, 01 Oct 2013 10:59:45 GMT";
"Keep-Alive" = "timeout=5, max=100";
Server = Apache;
Vary = "Accept-Encoding";
} }, NSLocalizedDescription=Request failed: unacceptable content-type: text/html}
I just hid the JSON using kJSONlink. This should return a JSON.
This means that your server is sending "text/html" instead of the already supported types.
My solution was to add "text/html" to acceptableContentTypes set in AFURLResponseSerialization class. Just search for "acceptableContentTypes" and add #"text/html" to the set manually.
Of course, the ideal solution is to change the type sent from the server, but for that you will have to talk with the server team.
Setting my RequestOperationManager Response Serializer to HTTPResponseSerializer fixed the issue.
Objective-C
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
Swift
manager.responseSerializer = AFHTTPResponseSerializer()
Making this change means I don't need to add acceptableContentTypes to every request I make.
I took #jaytrixz's answer/comment one step further and added "text/html" to the existing set of types. That way when they fix it on the server side to "application/json" or "text/json" I claim it'll work seamlessly.
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
On the server side, I added:
header('Content-type: application/json');
into my .php code and this also fixed the problem.
I solve this problem from a different perspective.
I think if the server sends JSON data with Content-Type: text/html header. It doesn't mean the server guy intended to send you some html but accidentally changed to JSON. It does mean the server guy just doesn't care about what the Content-Type header is. So if the server guy doesn't care as the client side you better ignore the Content-Type header as well. To ignore the Content-Type header check in AFNetworking
manager.responseSerializer.acceptableContentTypes = nil;
In this way the AFJSONResponseSerializer (the default one) will serialize the JSON data without checking Content-Type in response header.
A simple way to enable to receive "text/plain" content type:
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/plain"];
Similarly if you wish to enable "text/html" content type:
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
I tried below line as per #Andrie answer but didn't work,
op.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
so after hunting more, I did work around to get it work successfully.
Here is my code snip.
AFHTTPRequestOperationManager *operation = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:url];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
AFJSONResponseSerializer *jsonResponseSerializer = [AFJSONResponseSerializer serializer];
NSMutableSet *jsonAcceptableContentTypes = [NSMutableSet setWithSet:jsonResponseSerializer.acceptableContentTypes];
[jsonAcceptableContentTypes addObject:#"text/plain"];
jsonResponseSerializer.acceptableContentTypes = jsonAcceptableContentTypes;
operation.responseSerializer = jsonResponseSerializer;
Hope this will help someone out there.
This is the only thing that I found to work
-(void) testHTTPS {
AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
[securityPolicy setAllowInvalidCertificates:YES];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager setSecurityPolicy:securityPolicy];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:[NSString stringWithFormat:#"%#", HOST] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"%#", string);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
If someone is using AFHTTPSessionManager then one can do like this to solve the issue,
I subclassed AFHTTPSessionManager where I'm doing like this,
NSMutableSet *contentTypes = [[NSMutableSet alloc] initWithSet:self.responseSerializer.acceptableContentTypes];
[contentTypes addObject:#"text/html"];
self.responseSerializer.acceptableContentTypes = contentTypes;
In my case, I don't have control over server setting, but I know it's expecting "application/json" for "Content-Type". I did this on the iOS client side:
manager.requestSerializer = [AFJSONRequestSerializer serializer];
refer to
AFNetworking version 2 content-type error
Just add this line :
operation.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
A good question always have multiple answers, to reduce and help you choose the right answer, here I am adding my own too. I have tested it and it works fine.
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:#"http://www.yourdomain.com/appname/data/ws/index.php/user/login/"]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:#"POST" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *json = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"%#", json);
//Now convert json string to dictionary.
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#", error.localizedDescription);
}];
I had a somehow similar problem working with AFNetworking from a Swift codebase so I'm just leaving this here in the remote case someone is as unlucky as me having to work in such a setup. If you are, I feel you buddy, stay strong!
The operation was failing due to "unacceptable content-type", despite me actually setting the acceptableContentTypes with a Set containing the content type value in question.
The solution for me was to tweak the Swift code to be more Objective-C friendly, I guess:
serializer.acceptableContentTypes = NSSet(array: ["application/xml", "text/xml", "text/plain"]) as Set<NSObject>
UIImage *image = [UIImage imageNamed:#"decline_clicked.png"];
NSData *imageData = UIImageJPEGRepresentation(image,1);
NSString *queryStringss = [NSString stringWithFormat:#"http://119.9.77.121/lets_chat/index.php/webservices/uploadfile/"];
queryStringss = [queryStringss stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
[manager POST:queryStringss parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
[formData appendPartWithFileData:imageData name:#"fileName" fileName:#"decline_clicked.png" mimeType:#"image/jpeg"];
}
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSDictionary *dict = [responseObject objectForKey:#"Result"];
NSLog(#"Success: %# ***** %#", operation.responseString, responseObject);
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
NSLog(#"Error: %# ***** %#", operation.responseString, error);
}];
I would like to make the following request from my app:
AFHTTPRequestOperationManager *requestManager = [[AFHTTPRequestOperationManager alloc] init];
requestManager.responseSerializer.acceptableContentTypes = [requestManager.responseSerializer.acceptableContentTypes setByAddingObject:#"application/json"];
requestManager.requestSerializer = [AFJSONRequestSerializer serializer];
[requestManager POST:urlString parameters:aParameters constructingBodyWithBlock:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"%#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"error: %#", error);
}];
Where aParameters is an NSDictionary with the following content:
NSDictionary *urlParams = #{#"username" : anUser.userName, #"password" : anUser.password};
When I make the request from my app with the user input of "anUsername" and "aPassword" I get the following log for the body in my servlet:
--Boundary+5738A89B2C391231
Content-Disposition: form-data; name="password"
aPassword
--Boundary+5738A89B2C391231
Content-Disposition: form-data; name="username"
anUsername
--Boundary+5738A89B2C391231--
multipart/form-data; boundary=Boundary+5738A89B2C391231
I was under the impression that using AFJSONRequestSerializer would send my request in the appropriate format, but as the log shows, it's multipart/form data. It is really hard (for me) to parse this kind of request (I'm parsing it in Java on the server side), so my question is: is it possible to send a json in the body of my request? Something like this:
{
"userName" : "anUsername",
"password" : "aPassword"
}
Any help would be appreciated.
For anyone concerned: Instead of using the POST:parameters:constructingBodyWithBlock:success:failure: method, you should use POST:parameters:success:failure:. The former performs a multipart form request, while the latter does url form encoding. Additionally, to send the params in JSON, the requestSerializer property of the AFHTTPRequestOperationManager instance should be an instance of AFJSONRequestSerializer (by default it is set to AFHTTPRequestSerializer)
It is really helpful to browse the implementation file of AFHTTPRequestOperationManager for details, it helped me sort this error out.
You don't need to send pure JSON in POST request, just send Parameters dictionary. Here is the sample code that is working for POST Request.
+ (void)login:(BOUser *)user responseBlock:(APIRequestResponseBlock)responseBlock {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:#"parse-application-id-removed" forHTTPHeaderField:#"X-Parse-Application-Id"];
[manager.requestSerializer setValue:#"parse-rest-api-key-removed" forHTTPHeaderField:#"X-Parse-REST-API-Key"];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
manager.securityPolicy.allowInvalidCertificates = YES;
NSString *URLString = [NSString stringWithFormat:#"%#login", BASE_URL_STRING];
NSDictionary *params = #{#"email": user.username,
#"password": user.password};
[manager POST:URLString parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
responseBlock(nil, FALSE, error);
}];
}
I hope it helps.
I'm trying out the new version 2.0 of AFNetworking and I'm getting the error above. Any idea why this is happening? Here's my code:
NSURL *URL = [NSURL URLWithString:kJSONlink];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
[[NSOperationQueue mainQueue] addOperation:op];
I'm using Xcode 5.0.
Also, here's the error message:
Error: Error Domain=AFNetworkingErrorDomain Code=-1016 "Request failed: unacceptable content-type: text/html" UserInfo=0xda2e670 {NSErrorFailingURLKey=kJSONlink, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0xda35180> { URL: kJSONlink } { status code: 200, headers {
Connection = "Keep-Alive";
"Content-Encoding" = gzip;
"Content-Length" = 2898;
"Content-Type" = "text/html";
Date = "Tue, 01 Oct 2013 10:59:45 GMT";
"Keep-Alive" = "timeout=5, max=100";
Server = Apache;
Vary = "Accept-Encoding";
} }, NSLocalizedDescription=Request failed: unacceptable content-type: text/html}
I just hid the JSON using kJSONlink. This should return a JSON.
This means that your server is sending "text/html" instead of the already supported types.
My solution was to add "text/html" to acceptableContentTypes set in AFURLResponseSerialization class. Just search for "acceptableContentTypes" and add #"text/html" to the set manually.
Of course, the ideal solution is to change the type sent from the server, but for that you will have to talk with the server team.
Setting my RequestOperationManager Response Serializer to HTTPResponseSerializer fixed the issue.
Objective-C
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
Swift
manager.responseSerializer = AFHTTPResponseSerializer()
Making this change means I don't need to add acceptableContentTypes to every request I make.
I took #jaytrixz's answer/comment one step further and added "text/html" to the existing set of types. That way when they fix it on the server side to "application/json" or "text/json" I claim it'll work seamlessly.
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
On the server side, I added:
header('Content-type: application/json');
into my .php code and this also fixed the problem.
I solve this problem from a different perspective.
I think if the server sends JSON data with Content-Type: text/html header. It doesn't mean the server guy intended to send you some html but accidentally changed to JSON. It does mean the server guy just doesn't care about what the Content-Type header is. So if the server guy doesn't care as the client side you better ignore the Content-Type header as well. To ignore the Content-Type header check in AFNetworking
manager.responseSerializer.acceptableContentTypes = nil;
In this way the AFJSONResponseSerializer (the default one) will serialize the JSON data without checking Content-Type in response header.
A simple way to enable to receive "text/plain" content type:
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/plain"];
Similarly if you wish to enable "text/html" content type:
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
I tried below line as per #Andrie answer but didn't work,
op.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
so after hunting more, I did work around to get it work successfully.
Here is my code snip.
AFHTTPRequestOperationManager *operation = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:url];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
AFJSONResponseSerializer *jsonResponseSerializer = [AFJSONResponseSerializer serializer];
NSMutableSet *jsonAcceptableContentTypes = [NSMutableSet setWithSet:jsonResponseSerializer.acceptableContentTypes];
[jsonAcceptableContentTypes addObject:#"text/plain"];
jsonResponseSerializer.acceptableContentTypes = jsonAcceptableContentTypes;
operation.responseSerializer = jsonResponseSerializer;
Hope this will help someone out there.
This is the only thing that I found to work
-(void) testHTTPS {
AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
[securityPolicy setAllowInvalidCertificates:YES];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager setSecurityPolicy:securityPolicy];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:[NSString stringWithFormat:#"%#", HOST] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"%#", string);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
If someone is using AFHTTPSessionManager then one can do like this to solve the issue,
I subclassed AFHTTPSessionManager where I'm doing like this,
NSMutableSet *contentTypes = [[NSMutableSet alloc] initWithSet:self.responseSerializer.acceptableContentTypes];
[contentTypes addObject:#"text/html"];
self.responseSerializer.acceptableContentTypes = contentTypes;
In my case, I don't have control over server setting, but I know it's expecting "application/json" for "Content-Type". I did this on the iOS client side:
manager.requestSerializer = [AFJSONRequestSerializer serializer];
refer to
AFNetworking version 2 content-type error
Just add this line :
operation.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
A good question always have multiple answers, to reduce and help you choose the right answer, here I am adding my own too. I have tested it and it works fine.
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:#"http://www.yourdomain.com/appname/data/ws/index.php/user/login/"]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:#"POST" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *json = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"%#", json);
//Now convert json string to dictionary.
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#", error.localizedDescription);
}];
I had a somehow similar problem working with AFNetworking from a Swift codebase so I'm just leaving this here in the remote case someone is as unlucky as me having to work in such a setup. If you are, I feel you buddy, stay strong!
The operation was failing due to "unacceptable content-type", despite me actually setting the acceptableContentTypes with a Set containing the content type value in question.
The solution for me was to tweak the Swift code to be more Objective-C friendly, I guess:
serializer.acceptableContentTypes = NSSet(array: ["application/xml", "text/xml", "text/plain"]) as Set<NSObject>
UIImage *image = [UIImage imageNamed:#"decline_clicked.png"];
NSData *imageData = UIImageJPEGRepresentation(image,1);
NSString *queryStringss = [NSString stringWithFormat:#"http://119.9.77.121/lets_chat/index.php/webservices/uploadfile/"];
queryStringss = [queryStringss stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
[manager POST:queryStringss parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
[formData appendPartWithFileData:imageData name:#"fileName" fileName:#"decline_clicked.png" mimeType:#"image/jpeg"];
}
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSDictionary *dict = [responseObject objectForKey:#"Result"];
NSLog(#"Success: %# ***** %#", operation.responseString, responseObject);
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
NSLog(#"Error: %# ***** %#", operation.responseString, error);
}];