AFNetworking accept content type error: {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.} - afnetworking

I am using AFNetworking to GET a plain/text:
let manager = AFHTTPRequestOperationManager()
manager.GET(url, parameters: nil, success: { (op: AFHTTPRequestOperation!, res: AnyObject!) -> Void in
},failure: { (op: AFHTTPRequestOperation!, er:NSError!) -> Void in
println(op,er)
})
The accept content types:
manager.responseSerializer.acceptableContentTypes
[text/javascript, application/json, text/json]
So I got error in failure block:
NSLocalizedDescription=Request failed: unacceptable content-type: text/plain}
Then i added text/plain in this way:
var set = manager.responseSerializer.acceptableContentTypes
set.insert("text/plain")
manager.responseSerializer.acceptableContentTypes = set
right now the types are:
manager.responseSerializer.acceptableContentTypes
[application/json, text/javascript, text/plain, text/json]
But i got the new error:
{ URL: http://192.168.1.9:8081/sec.jsp } { status code: 200, headers {
"Content-Length" = 44;
"Content-Type" = "text/plain; charset=utf-8";
Expires = "Thu, 01 Jan 1970 00:00:00 GMT";
Server = "Jetty(6.1.10)";
"Set-Cookie" = "JSESSIONID=tapmhct7hanv;Path=/";
} }>, Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x7fda31fb4a90 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.})
I think the question is because JSON can't read the response. But i have set it to text/plain, does it still try to parse the plain text as JSON?
I searched and try a way:
manager.responseSerializer = AFJSONResponseSerializer(readingOptions: NSJSONReadingOptions.AllowFragments)
But the error is:
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Garbage at end.) UserInfo=0x7ff4b1790660 {NSDebugDescription=Garbage at end.})

Man, this is what I added in when I config my AFNetworking class and it works fine.
The reason you got that 3840 error, is because your API server returns an integer or even empty stuff, which ios json parser failed.
Can u make sure in swift, the phrase your are using is correct way?
_delegateClient.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer
serializerWithReadingOptions:NSJSONReadingAllowFragments];
[manager GET:url parameters:parameters progress:nil
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"request: %#\n", responseObject);
completionBlock(responseObject,nil);
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"Error: %#\n", error);
completionBlock(nil,error);
}];

Related

AFHTTPRequestOperationManager file upload returns 500 server error

Im trying to upload camera taken photo to webservice with afnetworking.
this my upload part code :
CGSize newSize = CGSizeMake(500.0f, 500.0f);
UIGraphicsBeginImageContext(newSize);
[_imagedata drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *imgData = UIImageJPEGRepresentation(newImage, 0.9f);
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"user": "test_user"};
[manager POST:#"http://www.mywebsite.com/webservice.aspx" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[formData appendPartWithFormData:imgData name:#"image"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
Im using Asp.net as my webservice.
this is my server side code :
string USER = Server.UrlDecode(Request["user"]),
SqlParameter prmUser = sc.Parameters.Add("#user", SqlDbType.VarChar);
prmUser.Direction = ParameterDirection.Input;
prmUser.Value = USER;
HttpFileCollection MyFileCollection = Request.Files;
if (MyFileCollection != null && MyFileCollection.Count > 0 && MyFileCollection[0] != null)
{
SqlParameter prmImage = sc.Parameters.Add("#Image", SqlDbType.Image);
prmImage.Direction = ParameterDirection.Input;
byte[] buf = new byte[MyFileCollection[0].ContentLength];
MyFileCollection[0].InputStream.Read(buf, 0, MyFileCollection[0].ContentLength);
prmPhoto.Value = buf;
}
sc.ExecuteNonQuery();
now everytime i run program this error apears :
Error: Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: internal server error (500)" UserInfo=0x1555ff60 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x16a94010> { URL: http://www.mywebsite.com/webservice.aspx } { status code: 500, headers {
Connection = close;
"Content-Length" = 3420;
"Content-Type" = "text/html; charset=utf-8";
Date = "Wed, 01 Apr 2015 15:56:21 GMT";
Server = "Microsoft-IIS/8.5";
Via = "1.1 magellan-front (squid/3.5.1)";
"X-AspNet-Version" = "4.0.30319";
"X-Cache" = "MISS from magellan-front";
"X-Powered-By" = "ASP.NET";
} }, NSErrorFailingURLKey=http://www.mywebsite.com/webservice.aspx, NSLocalizedDescription=Request failed: internal server error (500),
the detailed error :
[HttpRequestValidationException (0x80004005): A potentially dangerous Request.Form value was detected from the client (image="...�5�Ƨ&�����<I
�(�ep��K�,�=mp�...").]
also the webservice works well with android HttpFileUpload method.
I was trying to find the basics of this, here is the link
What it seems from your code is that the client side seems to have a issue. Why don't you try using appendPartWithFileURL:name:fileName:mimeType:error:, and say if that doesn't work then the issue has to be from server side.
I don't know much about ASP.NET, but could you once verify your way how you are trying to read the file. Here is the link where in I found something interesting you might wanna try implementing.
The enumerator on the HttpFileCollection returns the keys (names) of the files, not the HttpPostedFileBase objects. Once you get the key, use the Item ([]) property with the key (filename) to get the HttpPostedFileBase object.
foreach (string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
...
}
Let me know if this doesn't work.
Try uploading the image as a file (appendPartWithFileData) rather than as form data (appendPartWithFormData), and setting a content-type:
[formData appendPartWithFileData:imgData name:#"image"
fileName:#"image.jpg" mimeType:#"image/jpeg"];
Also see https://stackoverflow.com/a/15413152/1469259

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

(Cocoa error 3840.)" (Invalid value around character 0.) AFNetworking

I've been getting the following error when using the GET method to retrieve a file from a server:
Error: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Invalid value around character 0.) UserInfo=0x16e81ed0 {NSDebugDescription=Invalid value around character 0.}
I've tried a number of different things and I believe it could be something to do with the JSON format on the file that I'm trying to get.
Here is the code I've been using:
_username = #"JonDoe";
NSDictionary *parameters = #{ #"username" : _username};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/plain"];
[manager GET:#"http://.........."
parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
My POST method works fine. I just can't seem to fix this issue with the GET. Any ideas? Thank you.
Judging by the discussion in the comments it appears that your GET request is successful (response code 200), but the response body is not valid JSON (nor a JSON fragment) as you have requested by your use of AFJSONResponseSerializer. A basic AFHTTPResponseSerializer can be used for responses that are not JSON.
I am pretty sure that you have a valid response from server but your response is not a valid format in JSON, probably because you have carachters in front of first { .
Please try this: Put the same URL address manually in your browser and you will see the culprit in the response. Hope it helped.
Hey guys this is what I found to be my issue: I was calling Alamofire via a function to Authenticate Users: I used the function "Login User" With the parameters that would be called from the "body"(email: String, password: String) That would be passed
my errr was exactly:
optional(alamofire.aferror.responseserializationfailed(alamofire.aferror.responseserializationfailurereason.jsonserializationfailed(error domain=nscocoaerrordomain code=3840 "invalid value around character 0." userinfo={nsdebugdescription=invalid value around character 0
character 0 is the key here: meaning the the call for the "email" was not matching the parameters: See the code below
func loginUser(email: String, password: String, completed: #escaping downloadComplete) {
let lowerCasedEmail = email.lowercased()
let header = [
"Content-Type" : "application/json; charset=utf-8"
]
let body: [String: Any] = [
"email": lowerCasedEmail,
"password": password
]
Alamofire.request(LOGIN_USER, method: .post, parameters: body, encoding: JSONEncoding.default, headers: header).responseJSON { (response) in
if response.result.error == nil {
if let data = response.result.value as? Dictionary<String, AnyObject> {
if let email = data["user"] as? String {
self.userEmail = email
print(self.userEmail)
}
if let token = data["token"] as? String {
self.token_Key = token
print(self.token_Key)
}
"email" in function parameters must match the let "email" when parsing then it will work..I no longer got the error...And character 0 was the "email" in the "body" parameter for the Alamofire request:
Hope this helps

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.

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