AFNetworking HTTP delete use body instead of URL - ios

I'm trying to send a HTTP DELETE request to a RESTful Django web service from my iOS app.
I use AFNetworking 2.0 (2.4).
After analysing the AFHTTPREquestOperation in the success block of my API call, i found that the body of the request is nil. The parameters URL encoded and sent in the URL.
<AFHTTPRequestOperation: 0x10c587940,
state: isFinished,
cancelled: NO
request: <NSMutableURLRequest: 0x10c521ab0> {
URL: https://anURL.com/connections?data%5Bconnections%5D%5B%5D%5Bid%5D=106 },
response: <NSHTTPURLResponse: 0x10c5c7590> {
URL: anURL.com/
connections?data%5Bconnections%5D%5B%5D%5Bid%5D=106
}
{ status code: 200, headers {
Connection = "Keep-Alive";
"Content-Type" = "application/json";
Date = "Tue, 05 Aug 2014 14:07:53 GMT";
"Keep-Alive" = "timeout=5, max=100";
Server = "Apache/2.4.7 (Ubuntu)";
"Transfer-Encoding" = Identity;
} }>
Now I wonder if it is possible to send the parameters in the body of the request, as done with HTTP POST instead of sending them in the URL. Is that possible?
How to do it using AFNetworking?
How i send atm:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager DELETE:host_url parameters:params success:success failure:failure];
The body i want to send(its whats in the "params" parameter above):
{
"data": {
"connections": [
{
"id": 92
},
{
"id": 91
}
]
}
}

Had same problem. As question is still open, will post answer here. All you need to do, is change HTTP methods, that encode parameters as a query string (by default GET, HEAD, and DELETE). Request serializer has HTTPMethodsEncodingParametersInURI property for that. Just set it to GET, HEAD and you are done:
serializer.HTTPMethodsEncodingParametersInURI = [NSSet setWithObjects:#"GET", #"HEAD", nil];

Answer provided by #f3n1kc is corrected, but just in case you looking for Swift Version:
let manager = AFHTTPSessionManager()
manager.requestSerializer = AFHTTPRequestSerializer()
manager.requestSerializer.HTTPMethodsEncodingParametersInURI = ["GET", "HEAD"]

Related

JSON Parsing getting Error NSErrorFailingURLKey in IOS

I am trying to print JSON response in first log.But whenever i try to get response from this URL and also from this URL .But whenever i make a request i am getting this error.
NSErrorFailingURLKey=http://wptrafficanalyzer.in/p/demo1/first.php/countries/, NSLocalizedDescription=Request failed: unacceptable content-type: text/html, com.alamofire.serialization.response.error.data
This is my Log File
2016-01-15 12:19:25.618 JSOnParsingWithActorList[3153:58905] Error: Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/html" UserInfo={com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x78e25230> { URL: http://wptrafficanalyzer.in/p/demo1/first.php/countries/ } { status code: 200, headers {
"Cache-Control" = "max-age=3600";
Connection = "Keep-Alive";
"Content-Encoding" = gzip;
"Content-Length" = 490;
"Content-Type" = "text/html";
Date = "Fri, 15 Jan 2016 06:27:55 GMT";
Expires = "Fri, 15 Jan 2016 07:27:55 GMT";
"Keep-Alive" = "timeout=5, max=100";
Server = "Apache/2.2.22 (Ubuntu)";
Vary = "Accept-Encoding";
"X-Powered-By" = "PHP/5.3.10-1ubuntu3.21";
} }, NSErrorFailingURLKey=http://wptrafficanalyzer.in/p/demo1/first.php/countries/, NSLocalizedDescription=Request failed: unacceptable content-type: text/html, com.alamofire.serialization.response.error.data=<7b22636f 756e7472 69657322 3a5b7b22 636f756e 7472796e 616d6522 3a22496e 64696122 2c22666c 6167223a 22687474 703a5c2f 5c2f7770 74726166 66696361 6e616c79 7a65722e 696e5c2f 705c2f64 656d6f31 5c2f696e 6469612e 706e6722 2c226c61 6e677561 6765223a 2248696e 6469222c 22636170 6974616c 223a224e 65772044 656c6869 222c2263 75727265 6e637922 3a7b2263 6f646522 3a22494e 52222c22 63757272 656e6379 6e616d65 223a2252 75706565 227d7d2c 7b22636f 756e7472 796e616d 65223a22 50616b69 7374616e 222c2266 6c616722 3a226874 74703a5c 2f5c2f77 70747261 66666963 616e616c 797a6572 2e696e5c 2f705c2f 64656d6f 315c2f70 616b6973 74616e2e 706e6722 2c226c61 6e677561 6765223a 22557264 75222c22 63617069 74616c22 3a224973 6c616d61 62616422 2c226375 7272656e 6379223a 7b22636f 6465223a 22504b52 222c2263 75727265 6e63796e 616d6522 3a225061 6b697374 616e6920 52757065 65227d7d 2c7b2263 6f756e74 72796e61 6d65223a 22537269 204c616e 6b61222c 22666c61 67223a22 68747470 3a5c2f5c 2f777074 72616666 6963616e 616c797a 65722e69 6e5c2f70 5c2f6465 6d6f315c 2f737269 6c616e6b 612e706e 67222c22 6c616e67 75616765 223a2253 696e6861 6c61222c 22636170 6974616c 223a2253 7269204a 61796177 61726465 6e617075 7261204b 6f747465 222c2263 75727265 6e637922 3a7b2263 6f646522 3a22534b 52222c22 63757272 656e6379 6e616d65 223a2253 7269204c 616e6b61 6e205275 70656522 7d7d2c7b 22636f75 6e747279 6e616d65 223a2243 68696e61 222c2266 6c616722 3a226874 74703a5c 2f5c2f77 70747261 66666963 616e616c
I am using AFNetworking for making URL call.I check this url's in Android.This URL content-type is Application/JSON but in IOS i am getting header content-type text/html.From this URL I am getting sucessful response from URL in JSON format.Please help for solve this issue.
This is my ViewController.m file
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:#"http://wptrafficanalyzer.in/p/demo1/first.php/countries/"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"%# %#",response);
}
}];
[dataTask resume];
}
Add this code:
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
After this :
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
It is well explained here : Upload an sqlite file
Your server page is returning text/html, but AFURLSessionManager is expecting JSON.
Edit:
As the above solution didn't work out , i found this link containing all possible solution for this error : Request failed: unacceptable content-type: text/html

How to set Content-Type in AFNetworking?

I want to set "application/x-www-form-urlencoded" with post method
So ,I set request.requestSerializer.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") But When I set the request to the server the Content-Type is not change what happen?
this is error
{com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x7c166450> { URL: http://test.com } { status code: 404, headers {
Connection = "keep-alive";
"Content-Length" = 434;
"Content-Type" = "text/html";
Date = "Mon, 13 Jul 2015 11:18:18 GMT";
Server = "nginx/1.0.15";
} }, NSErrorFailingURLKey=http://text.com, NSLocalizedDescription=Request failed: not found (404),
this is my code:
var request = AFHTTPRequestOperationManager();
request.requestSerializer = AFHTTPRequestSerializer()
request.requestSerializer.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.POST(url, parameters: parameters, success: { (oper,obj) -> Void in
// do something
}) { (oper, error) -> Void in
// do something with error
}
It's exactly what the error says: your server is sending back a webpage (HTML) for a 400 status code, when you were expecting JSON.
A 400 status code is used a bad request, which is probably generated because you're sending URL-form-encoded text as application/json. What you really want is to use AFJSONRequestSerializer for your request serializer.
manager.requestSerializer = [AFJSONRequestSerializer serializer];
I am not doing any code of AFNetworking in Swift so I can't tell you code of that but you can get idea from objective-c code.
I hope it will help you.

AFNetworking: How to set Content-Type HTTP Header in request?

The way to register my clients with my API server using command-line is
curl -d'{"email": "e", "memberExternalId": "m"}' -H"Content-Type: application/json" https://api-myapp.com/register
{"memberId":"78f7f8a4-a8c9-454a-93a8-6633a1076781","clientId":"111322610106743984083443169763434312591","clientSecret":"255682200164339900511209955730378006963"}
I am trying to do similar thing with Objective-C using AFNetworking. My current code looks like
- (void)connectWithServer {
NSLog(#"connecting with server");
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/json"];
[manager POST:#"http://api-myapp.com/register"
parameters:#{#"email": #"e", #"memberExternalId": #"m"}
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
What I see in my console is
2014-11-15 15:13:29.719 myapp-ios[42377:70b] Error: Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: bad request (400)" UserInfo=0xb61e130 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0xb3071b0> { URL: http://api-myapp.com/register } { status code: 400, headers {
"Accept-Ranges" = none;
Connection = close;
"Content-Length" = 206;
"Content-Type" = "text/html";
Date = "Sat, 15 Nov 2014 23:13:29 GMT";
Server = "WildFly/8";
"X-Powered-By" = "Undertow/1";
} }, NSErrorFailingURLKey=http://api-myapp.com/register, NSLocalizedDescription=Request failed: bad request (400), com.alamofire.serialization.response.error.data=<636f6d2e 66617374 6572786d 6c2e6a61 636b736f 6e2e636f 72652e4a 736f6e50 61727365 45786365 7074696f 6e3a2055 6e726563 6f676e69 7a656420 746f6b65 6e202765 6d61696c 273a2077 61732065 78706563 74696e67 20282774 72756527 2c202766 616c7365 27206f72 20276e75 6c6c2729 0a206174 205b536f 75726365 3a20696f 2e756e64 6572746f 772e7365 72766c65 742e7370 65632e53 6572766c 6574496e 70757453 74726561 6d496d70 6c403132 66336263 613b206c 696e653a 20312c20 636f6c75 6d6e3a20 375d>, NSUnderlyingError=0xb60f160 "Request failed: unacceptable content-type: text/html"}
What am I doing wrong? why the Content-Type is still text/html?
It's exactly what the error says: your server is sending back a webpage (HTML) for a 400 status code, when you were expecting JSON.
A 400 status code is used a bad request, which is probably generated because you're sending URL-form-encoded text as application/json. What you really want is to use AFJSONRequestSerializer for your request serializer.
manager.requestSerializer = [AFJSONRequestSerializer serializer];

AFNetorking in Swift project -- "Error: Request failed: unacceptable content-type: text/html"

I am implementing AFNetworking with CocoaPods into a Swift project. I am used to programming in Ruby and I am very new to iOS development. Cocoapods was tricky to get working properly in my project but I can now successfully access the AFNetworking library.
What I am trying to do is hit a form with a POST and get a response as "text/html" that I can parse so that I can tell if it saves. This is not an API per se, but a form generated by InfusionSoft. A user will enter an email address and I will send that off to an API for storage. Here is the code I am using:
let manager = AFHTTPRequestOperationManager()
var parameters = ["inf_form_xid": "MY_ACCESS_ID",
"inf_form_name": "Webform in Content App",
"infusionsoft_version": "1.34.0.35",
"inf_field_email": self.emailTextField.text]
manager.POST( "https://ns166.infusionsoft.com/app/form/process/REALLYLONGUNIQUEID",
parameters: parameters,
success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in
println("JSON: " + responseObject.description)
},
failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in
println("Error: " + error.localizedDescription)
})
And the error that I am receiving this as a response from AFNetworking:
Error: Request failed: unacceptable content-type: text/html
At the end of the day, I want to verify that it was saved by the server before I allow the user to continue in the application.
Any help is greatly appreciated.
You have to add content-type allowed for the response.
You could do that for json content :
manager.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json")
EDIT
If you're using AFNetworking 2.0, from AFNetworking wiki :
"By default, AFHTTPRequestOperationManager and AFHTTPSessionManager have JSON serializers."
So you should maybe try to change the response serializer in your manager like this :
manager.responseSerializer = AFHTTPResponseSerializer()
This means that your server is sending "text/html" instead of the already supported types.You can either add acceptable content type as "text/html" or ensure that you are properly sending json format from the server side.By default the content type for afnetworking is json in objective c.Dont know about swift.
Reference :Request failed: unacceptable content-type: text/html using AFNetworking 2.0
I am not sure about swift but in objective c ,after searching for answer i came across the solution which working very well for me .
Below is the code snippet:
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;

parse json from post request ios afnetworking

I'm working on an iOS app (pretty new to iOS) and I have my registration flow working where i post data to my server... The server returns JSON, but my question is, how do I parse that into variables?
The data that it returns is:
{"token":"67f41f60-9a9a-11e3-8310-11b6baf18c40","userId":13,"stationId":1}
The code I'm using to make the post request is:
[manager POST:#"http://localhost:3000/service/register_user/" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error!!!!!: %#", error);
}];
Also, when I make the post request, this is what I get in the log in xcode
2014-02-20 20:50:39.799 FlashoverResponse[4668:70b] Error!!!!!: Error Domain=AFNetworkingErrorDomain Code=-1016 "Request failed: unacceptable content-type: text/html" UserInfo=0x8a5e4f0 {NSErrorFailingURLKey=http://localhost:3000/service/register_user/, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0x8a5e200> { URL: http://localhost:3000/service/register_user/ } { status code: 200, headers {
Connection = "keep-alive";
"Content-Length" = 74;
"Content-Type" = "text/html; charset=utf-8";
Date = "Fri, 21 Feb 2014 01:50:39 GMT";
"X-Powered-By" = Express;
} }, NSLocalizedDescription=Request failed: unacceptable content-type: text/html}
Is your server configured to respond in text/json application/json?
and/or have you set this?
manager.responseSerializer.acceptableContentTypes
it takes a NSSet of content types this parser will attempt to parse, if you cannot change the server to respond in json you can add text/html into that set, so the parser will parse it anyway.

Resources