JSON Parsing getting Error NSErrorFailingURLKey in IOS - 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

Related

Get the value of Error-Message in failure block of AFHTTPRequestOperation

I need to get the value of Error-Message in the failure block of my request.
Here's the error:
Error Domain=com.alamofire.error.serialization.response Code=-1011
"Request failed: bad request (400)" UserInfo=0x165151b0
{NSErrorFailingURLKey=http://203.125.112.203:8090/megumi01/api/zipData?lastSynced=1441161682,
com.alamofire.serialization.response.error.response= { URL:
http://203.125.112.203:8090/megumi01/api/zipData?lastSynced=1441161682
} { status code: 400, headers {
"Access-Control-Allow-Headers" = "x-requested-with, Authorization, Content-Type, Accept";
"Access-Control-Allow-Methods" = "POST, GET, OPTIONS, DELETE, PUT";
"Access-Control-Allow-Origin" = "*";
"Access-Control-Max-Age" = 3600;
"Cache-Control" = "no-cache, no-store, max-age=0, must-revalidate";
Connection = close;
"Content-Type" = "application/json;charset=UTF-8";
Date = "Wed, 02 Sep 2015 10:38:57 GMT";
"Error-Code" = 0808;
"Error-Message" = "No updates available";
Expires = 0;
Pragma = "no-cache";
Server = "Apache-Coyote/1.1";
"Transfer-Encoding" = Identity;
"X-Application-Context" = "application:9090";
"X-Content-Type-Options" = nosniff;
"X-Frame-Options" = DENY;
"X-XSS-Protection" = "1; mode=block"; } }, NSLocalizedDescription=Request failed: bad request (400)}
I have tried putting "error" into NSData so I could convert it to NSDictionary but it becomes nil.
May I know how could I get the value of the custom header "Error-Message"?
TYIA!
below code may help you. try it.
NSLog(#"status code :%ld",(long)[operation.response statusCode]);
NSLog(#"Failure Response %#, %#", error, operation.response.description);
After thinking straightly, I was able to get the proper way to get the custom header in failure block of AFHTTPRequestOperation.
NSDictionary *userInfo = [error userInfo];
NSHTTPURLResponse *alamofireResponse = [userInfo objectForKey:#"com.alamofire.serialization.response.error.response"];
NSDictionary *allHeaders = [alamofireResponse allHeaderFields];
NSString *customMessage = [allHeaders objectForKey:#"Error-Message"];

Request failed: internal server error (500) and Cocoa error 3840, Invalid value around character 0 responses AFNetworking

It appears to be working in web:
Web Response Headers:
Connection:keep-alive
Content-Length:394
Content-Type:application/json
Date:Sun, 22 Mar 2015 18:36:06 GMT
Server:nginx/1.6.2
Vary:Accept-Encoding
X-Powered-By:Express
Web Request Headers:
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Authorization:Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJfaWQiOiI1NDVjYzNjYzQ2N2I3YjAyMDBhMWNkOWEiLCJpYXQiOjE0MjcwNDM3Mzk1NjQsImV4cCI6MTQ5MDExNTczOTU2NH0.Xqm-b12QWcEa6MPXyKa1E8m88hGZI9KfJl7Img3mACU
Connection:keep-alive
Content-Length:225
Content-Type:application/json;charset=UTF-8
Web Request Payload:
{"id":"550f15122cc2708c2d9c65b8","users":["xiruken#gmail.com"],"welcomeMessage":"Hi there. We’ll be using Next24 to keep track of our daily high priority items as a group during this project.","newUser":"xiruken#gmail.com"}
But not working in my native iOS project using objective-C...
Same parameters:
NSDictionary query:
{
id = 550f15122cc2708c2d9c65b8;
newUser = "xiruken#gmail.com";
users = (
"xiruken#gmail.com"
);
welcomeMessage = "Hi there. We will be using Next24 to keep track of our daily high priority items as a group during this project.";
}
AFNetworking code:
-(AFHTTPSessionManager *)sessionManager2{
if(!_sessionManager2){
_sessionManager2 = [[AFHTTPSessionManager alloc] initWithBaseURL: [NSURL URLWithString:API_URL]];
AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
[securityPolicy setAllowInvalidCertificates:YES];
[_sessionManager2 setSecurityPolicy:securityPolicy];
_sessionManager2.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions: NSJSONReadingAllowFragments];
NSArray *acceptedTypes = #[#"text/html", #"application/json", #"text/plain"];
_sessionManager2.responseSerializer.acceptableContentTypes = [NSSet setWithArray:acceptedTypes];
//add token
if([Helpers isLoggedIn]){
UserDM *user = [UserDM loadCustomObjectWithKey:DEFAULT_CURRENT_USER];
[self.sessionManager2.requestSerializer setValue:[NSString stringWithFormat:#"Bearer %#", user.accessToken] forHTTPHeaderField:#"Authorization"];
}
}
return _sessionManager2;
}
Using AFJSONResponseSerializer is giving me this error:
2015-03-23 03:28:26.773 Next25[5801:302572] Failed! Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Invalid value around character 0.) UserInfo=0x7fdbb252a6e0 {NSDebugDescription=Invalid value around character 0., NSUnderlyingError=0x7fdbb252c410 "Request failed: internal server error (500)"}
I even allowFragments and even set acceptableContentTypes
And changing it to AFHTTPResponseSerializer is giving me a different error:
2015-03-23 03:30:30.797 Next25[5852:303849] Failed! Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: internal server error (500)" UserInfo=0x7fb129e4e930 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x7fb129e36320> { URL: https://myproject.com/api/projects/550f15122cc2708c2d9c65b8/invite_users } { status code: 500, headers {
Connection = "keep-alive";
"Content-Length" = 21;
"Content-Type" = "text/html";
Date = "Sun, 22 Mar 2015 19:26:56 GMT";
Server = "nginx/1.6.2";
Vary = "Accept-Encoding";
"X-Powered-By" = Express;
} }, NSErrorFailingURLKey=https://myproject.com/api/projects/550f15122cc2708c2d9c65b8/invite_users, com.alamofire.serialization.response.error.data=<496e7465 726e616c 20536572 76657220 4572726f 72>, NSLocalizedDescription=Request failed: internal server error (500)}

Vimeo API - unacceptable content-type: text/plain

I am using Vimeo API in my iOS application. But since few days it has stopped working, It gives me error while I am trying to upload any videos.
Following is the way, I am creating the request
NSURL *uploadURL = [NSURL URLWithString:endpoint];
OAMutableURLRequest *req = [[OAMutableURLRequest alloc] initWithURL:uploadURL consumer:self._oaconsumer token:self._authToken realm:nil signatureProvider:self._sigProv];
[req setTimeoutInterval:60.0];
[req setHTTPMethod:#"PUT"];
[req setValue:[NSString stringWithFormat:#"%ld",(unsigned long)self._byteSizeOfVideo] forHTTPHeaderField:#"Content-Length"];
[req setValue:#"video/quicktime" forHTTPHeaderField:#"Content-Type"];
and following error message i received,
Printing description of error:
Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: bad request (400)" UserInfo=0x1705bc80 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x15d1ff60> { URL: http://1511655313.cloud.vimeo.com/upload_multi?ticket_id=75225c91f65b14315902b8bee5fbbc44&signature=6126962b362c9c0777bce88556211572 } { status code: 400, headers {
"Access-Control-Allow-Origin" = "*";
Connection = close;
"Content-Length" = 28;
"Content-Type" = "text/plain";
Date = "Thu, 12 Feb 2015 15:46:12 GMT";
Server = "Vimeo/1.0";
} }, NSErrorFailingURLKey=http://1511655313.cloud.vimeo.com/upload_multi?ticket_id=75225c91f65b14315902b8bee5fbbc44&signature=6126962b362c9c0777bce88556211572, NSLocalizedDescription=Request failed: bad request (400), com.alamofire.serialization.response.error.data=<5369676e 61747572 65205661 6c696461 74696f6e 20666169 6c65640a>, NSUnderlyingError=0x15d237a0 "Request failed: unacceptable content-type: text/plain"}
Please do needful help.
Thank you !
Finally I found the bug,
While fetching the ticket-id, I am getting the following response
<?xml version="1.0" encoding="UTF-8"?>
<rsp generated_in="0.0308" stat="ok">
<ticket endpoint="http://1511635510.cloud.vimeo.com/upload_multi?ticket_id=090b9f68cce28467537cc6cc2d921c4d&signature=a9362ca1ec4bc8e624ef1e5d274ccb6e" endpoint_secure="https://1511635510.cloud.vimeo.com/upload_multi?ticket_id=090b9f68cce28467537cc6cc2d921c4d&signature=a9362ca1ec4bc8e624ef1e5d274ccb6e" host="1511635510.cloud.vimeo.com" id="090b9f68cce28467537cc6cc2d921c4d" max_file_size="5363328222"/>
</rsp>
Now here I am using enpoint url for uploading videos but in the endpoint url I found
& in place of & and It has wasted my lots of time.

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

RESTKit 2.0: AFHTTPClient with text/html

I'm using RESTKit v0.20.3. Since I'm not expecting a responseObject, I decided to use AFHTTPClient to POST. I have the following Code:
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
httpClient.parameterEncoding = AFJSONParameterEncoding;
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
[httpClient setDefaultHeader:#"Accept" value:#"application/json"];
[httpClient postPath:#"/update" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"AFJSONRequestOperation Alt response MIMEType %#",[responseObject MIMEType]);
[self.navigationController dismissViewControllerAnimated:YES completion:nil];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"***ERROR*****: %#", [error localizedDescription]);
}];
Here is my log
2014-04-01 16:43:01.125 App[13181:60b] E restkit.network:RKObjectRequestOperation.m:209 POST 'http://api.domain.com' (200 OK) [0.1158 s]: Error Domain=AFNetworkingErrorDomain Code=-1016 "Expected content type {(
"text/json",
"application/json",
"text/javascript"
)}, got text/html" UserInfo=0xccab6a0 {NSLocalizedRecoverySuggestion=<!DOCTYPE html><html><head><title></title><link rel="stylesheet" href="/stylesheets/style.css"></head><body><h1>Not Found</h1><h2>404</h2><pre>Error: Not Found
at Object.handle (/var/app/current/app.js:175:15)
at next (/var/app/current/node_modules/express/node_modules/connect/lib/proto.js:193:15)
at pass (/var/app/current/node_modules/express/lib/router/index.js:110:24)
at Router._dispatch (/var/app/current/node_modules/express/lib/router/index.js:173:5)
at Object.router (/var/app/current/node_modules/express/lib/router/index.js:33:10)
at next (/var/app/current/node_modules/express/node_modules/connect/lib/proto.js:193:15)
at SessionStrategy.module.exports.strategy.pass (/var/app/current/node_modules/passport/lib/middleware/authenticate.js:314:9)
at SessionStrategy.authenticate (/var/app/current/node_modules/passport/lib/strategies/session.js:61:12)
at pass (/var/app/current/node_modules/passport/lib/authenticator.js:333:31)
at deserialized (/var/app/current/node_modules/passport/lib/authenticator.js:345:7)</pre></body></html>, AFNetworkingOperationFailingURLRequestErrorKey=<NSMutableURLRequest: 0xda43280> { URL: http://api.domain.com/update }, NSErrorFailingURLKey=http://api.domain.com/update, NSLocalizedDescription=Expected content type {(
"text/json",
"application/json",
"text/javascript"
)}, got text/html, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0xdd50720> { URL: http://api.domain.com/update } { status code: 200, headers {
"Content-Length" = 1083;
"Content-Type" = "text/html; charset=utf-8";
Date = "Tue, 01 Apr 2014 23:43:12 GMT";
"Proxy-Connection" = "Keep-alive";
Server = "nginx/1.4.3";
"X-Powered-By" = Express;
} }}
2014-04-01 16:43:01.126 App[13181:60b] ***ERROR*****: Expected content type {(
"text/json",
"application/json",
"text/javascript"
)}, got text/html
I get the error is in receiving text/html, but how can I tell AFHTTPClient to expect text/html?
I tried adding:
[AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:#"text/html"]];
that returns:
2014-04-01 16:48:13.110 App[13289:60b] ***ERROR*****: The operation couldn’t be completed. (Cocoa error 3840.)
If I use AFHTTPRequestOperation, how do I pass parameters to it? I'm using RESTKit, so I can't use AFNetworking 2.0. Code Example would be greatly appreciated!
If you check the content of the HTML it actually says:
<h1>Not Found</h1><h2>404</h2>
So, the problem is not that the page you request doesn't exist rather than the returned content type being wrong.
Verify the URL and path that you are using.

Resources