Can't make POST request - AFNetworking - ios

I'm pretty new to Xcode, and I'm trying to make a POST request. I searched on Google and found this AFNetworking library. I've read some documentation but they all say different things. So now I use their own example on a POST request and my code looks like this:
- (void)viewDidLoad {
[super viewDidLoad];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"fName": #"firstname", #"lName": #"lastname"};
[manager POST:#"http://00000.1111.ovh/api/Account/register" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
And then I get this error:
Error: Error Domain=com.alamofire.error.serialization.response
Code=-1011 "Request failed: bad request (400)"
UserInfo={com.alamofire.serialization.response.error.response= { URL: http://00000.1111.ovh/api/Account/register } {
status code: 400, headers {
"Content-Length" = 159;
"Content-Type" = "application/json; charset=utf-8";
Date = "Sun, 15 Nov 2015 12:11:57 GMT";
Server = "Microsoft-IIS/8.5";
"X-Powered-By" = "ASP.NET"; } }, NSErrorFailingURLKey=http://00000.1111.ovh/api/Account/register,
com.alamofire.serialization.response.error.data=<7b226d65 73736167
65223a22 54686520 72657175 65737420 69732069 6e76616c 69642e22
2c226d6f 64656c53 74617465 223a7b22 6c6f6769 6e2e7573 65726e61
6d65223a 5b225468 65205573 6572206e 616d6520 6669656c 64206973
20726571 75697265 642e225d 2c226c6f 67696e2e 70617373 776f7264
223a5b22 54686520 50617373 776f7264 20666965 6c642069 73207265
71756972 65642e22 5d7d7d>, NSLocalizedDescription=Request failed: bad
request (400)}
Hope someone can help me!

You can better diagnose these issues if you translate the server's response into something you can parse/examine:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"fName": #"firstname", #"lName": #"lastname"};
[manager POST:#"http://00000.1111.ovh/api/Account/register" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON = %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error = %#", error);
if (operation.responseObject) {
NSLog(#"responseObject = %#", operation.responseObject);
} else {
NSLog(#"responseString = %#", operation.responseString);
}
}];
If you did that, you'd see that it responded with:
responseObject = {
message = "The request is invalid.";
modelState = {
"login.password" = (
"The Password field is required."
);
"login.username" = (
"The User name field is required."
);
};
}
Apparently, the request was missing the necessary authentication details.

Your request is sent correctly, but the server responded with HTTP code 400. Check the server's API documentation on how the request should look like.

Related

AFNetworking Request failing issue

I am having an issue where I am not able to connect to the API. This happens only with iOS8. It works fine with iOS7.
- (void)performSearch:(NSString*)type : (NSString*)keyword{
url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#", API, keyword]];
request = [NSURLRequest requestWithURL:url];
operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
credential = [NSURLCredential credentialWithUser:USERNAME password:PASSWORD persistence:NSURLCredentialPersistenceForSession];
[operation setCredential:credential];
[[NSOperationQueue mainQueue] addOperation:operation];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError *error = nil;
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
if (error) {
NSLog(#"Error serializing %#", error);
return;
}
[self parseJSON:JSON :keyword];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error : %#", error);
}];
[operation start];
}
The Error message I am getting.
Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: unauthorized (401)" UserInfo=0x7ff0650052f0 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x7ff062c5e4d0> { URL: https://distribution.virk.dk/cvr-permanent-prod-20150622/_search?q=anders } { status code: 401, headers {
Connection = "keep-alive";
"Content-Length" = 194;
"Content-Type" = "text/html";
Date = "Tue, 18 Aug 2015 09:36:09 GMT";
Server = "nginx/1.6.2";
"Www-Authenticate" = "Basic realm=\"Beskyttet adgang\"";
} }, NSErrorFailingURLKey=https://distribution.virk.dk/cvr-permanent-prod-20150622/_search?q=anders, com.alamofire.serialization.response.error.data=<3c68746d 6c3e0d0a 3c686561 643e3c74 69746c65 3e343031 20417574 686f7269 7a617469 6f6e2052 65717569 7265643c 2f746974 6c653e3c 2f686561 643e0d0a 3c626f64 79206267 636f6c6f 723d2277 68697465 223e0d0a 3c63656e 7465723e 3c68313e 34303120 41757468 6f72697a 6174696f 6e205265 71756972 65643c2f 68313e3c 2f63656e 7465723e 0d0a3c68 723e3c63 656e7465 723e6e67 696e782f 312e362e 323c2f63 656e7465 723e0d0a 3c2f626f 64793e0d 0a3c2f68 746d6c3e 0d0a>, NSLocalizedDescription=Request failed: unauthorized (401)}
Status code is 401, which means that your account or password is incorrect. I suggest that you should log out the params, and find out whether they are null or anything else

Getting Error when using AFNetwork to call a post API

I am trying to call a POST API on Instagram using AFNetworking, and my code to call is:
void (^mySuccessBlock)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary* userInfo = (NSDictionary*) responseObject;
if (block != nil) {
block(userInfo, nil);
}
};
void (^failureBlock)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Request Error: %#", error);
if (block != nil) {
block(nil, error);
}
};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *param=[[NSMutableDictionary alloc]init];
NSString * token =[defaults objectForKey:ACCESS_TOKEN];
[param setValue:token forKey:#"access_token"];
NSString *url=[NSString stringWithFormat:#"https://api.instagram.com/v1/media/%#/likes" , globalMediaId];
[manager POST:url parameters:param success:mySuccessBlock failure:failureBlock ];
But I am getting this error:
request Error: Error Domain=com.alamofire.error.serialization.response
Code=-1011 "Request failed: bad request (400)" UserInfo=0x7fb4c9698e00
{com.alamofire.serialization.response.error.response= { URL:
https://api.instagram.com/v1/media/853150485752748330_1509614005/likes
} { status code: 400, headers {
"Cache-Control" = "private, no-cache, no-store, must-revalidate";
Connection = "keep-alive";
"Content-Language" = en;
"Content-Length" = 114;
"Content-Type" = "application/json; charset=utf-8";
Date = "Mon, 29 Jun 2015 05:55:33 GMT";
Expires = "Sat, 01 Jan 2000 00:00:00 GMT";
Pragma = "no-cache";
"Set-Cookie" = "csrftoken=f4b5426f69b154c60e6785ba52100a09; expires=Mon, 27-Jun-2016 05:55:33 GMT; Max-Age=31449600; Path=/";
Vary = "Cookie, Accept-Language"; } }, NSErrorFailingURLKey=https://api.instagram.com/v1/media/853150485752748330_1509614005/likes,
com.alamofire.serialization.response.error.data=<7b226d65 7461223a
7b226572 726f725f 74797065 223a224f 41757468 50617261 6d657465
72457863 65707469 6f6e222c 22636f64 65223a34 30302c22 6572726f
725f6d65 73736167 65223a22 4d697373 696e6720 61636365 73735f74
6f6b656e 2055524c 20706172 616d6574 65722e22 7d7d>,
NSLocalizedDescription=Request failed: bad request (400)}
Does anyone know why I'm getting this?

Request failed: unacceptable content-type: application/osm3s+xml

I'm trying to send request to OpenStreetMap api, and I'm still failing to do so. Please help me out what's incorrect.
My method:
NSString *url = #"http://api.openstreetmap.fr/xapi?node[name=London]";
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/osm3s+xml"];
[manager setResponseSerializer:[AFXMLParserResponseSerializer new]];
[manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, NSData *responseObject) {
NSLog(#"DATA: %#", responseObject);
[self stopProgress];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
self.textView.text = error.description;
[self stopProgress];
}];
Error:
Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: application/osm3s+xml" UserInfo=0x1702e1e80 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x17403d080> { URL: http://api.openstreetmap.fr/xapi?node%5Bname=London%5D } { status code: 200, headers {
Connection = "Keep-Alive";
"Content-Encoding" = gzip;
"Content-Length" = 7166;
"Content-Type" = "application/osm3s+xml";
Date = "Sun, 25 Jan 2015 21:18:54 GMT";
"Keep-Alive" = "timeout=5, max=100";
Server = "Apache/2.2.22 (Debian)";
Vary = "Accept-Encoding";
} }, NSErrorFailingURLKey=http://api.openstreetmap.fr/xapi?node%5Bname=London%5D, com.alamofire.serialization.response.error.data=<3c3f786d 6c207665 7273696f 6e3d2231 2e302220 656e636f 64696e67 (... a lot of numbers ... )>, NSLocalizedDescription=Request failed: unacceptable content-type: application/osm3s+xml}
Your code:
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/osm3s+xml"];
Very clearly creates the header that OpenStreetMap is rejecting. Don't set that header: set it to a value like text/xml, which is documented as the right value.

Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: bad request (400)

I am using AFnetworking library to post data on server.
Following is my code to post data on server.
- (void) callLoginAPI:(NSDictionary *)dictProfile{
// 1
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:[dictProfile valueForKey:#"name"], #"username",
[dictProfile valueForKey:#"first_name"],#"first_name",
[dictProfile valueForKey:#"last_name"],#"last_name",
[dictProfile valueForKey:#"email"],#"email",
[dictProfile valueForKey:#"birthday"],#"dob",
[dictProfile valueForKey:#"gender"],#"gender",
[[dictProfile valueForKey:#"location"] valueForKey:#"name"],#"location",
[dictProfile valueForKey:#"timezone"],#"timezone",
#"",#"language",
[NSString stringWithFormat:#"http://graph.facebook.com/%#/picture?type=large",[dictProfile valueForKey:#"id"]],#"profile_pic_url",
#"",#"cover_pic_url",nil];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager POST:#"http://10.1.81.35:8000/api/login/" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
and in response I got following error
Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: bad request (400)" UserInfo=0x7c87b6f0 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x7cc220e0> { URL: http://10.1.81.35:8000/api/login/ } { status code: 400, headers {
Allow = "POST, OPTIONS";
"Content-Type" = "application/json";
Date = "Tue, 07 Oct 2014 10:45:08 GMT";
Server = "WSGIServer/0.1 Python/2.7.6";
Vary = "Accept, Cookie";
"X-Frame-Options" = SAMEORIGIN;
} }, NSErrorFailingURLKey=http://10.1.81.35:8000/api/login/, NSLocalizedDescription=Request failed: bad request (400), com.alamofire.serialization.response.error.data=<7b226465 7461696c 223a2022 4a534f4e 20706172 73652065 72726f72 202d204e 6f204a53 4f4e206f 626a6563 7420636f 756c6420 62652064 65636f64 6564227d>}
I am not able to understand why I got the such kind of error. What is missing in my code?
The error says it all: you got a 400 response from the server, meaning that what you sent was either not formatted properly, or the server just couldn't understand it.
Please add this line to your code,
i hope it help you.
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
I had experienced the same issue. In my case its only for upload Image with larger size. Our server has limited with max.upload size. I resized the image and uploaded, and the issue is gone.
You can resize the image with:
+ (UIImage*)imageWithImage:(UIImage*)image
scaledToSize:(CGSize)newSize;
{
UIGraphicsBeginImageContext( newSize );
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}

How to make a POST request in iOS?

I am trying to figure out how to make use of AFNetworking 2.0. I am trying to POST a login with a username and password.
This is my current attempt but something is not working as it does not get sent.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"loginName": #"password"};
[manager POST:#"http://xxxx.com/login" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
NSLog(#"Data saved");
MainViewController *mainView = [[MainViewController alloc] initWithNibName:#"MainViewController" bundle:nil];
mainView.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController: mainView animated:YES completion:nil];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
NSString *error_msg = (NSString *) error;
[self alertStatus:error_msg :#"Sign in Failed!" :0];
}];
}
} #catch (NSException * e) {
NSLog(#"Exception: %#", e);
[self alertStatus:#"Sign in Failed." :#"Error!" :0];
}
However nothing is happening, just keep getting this printout:
2014-04-16 20:14:09.903 Slidedrawer[9279:60b] Error: 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=0x8e78bd0 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
The response will be in JSON. Anyone know what I need to edit in the code or how to fix it?
JSON: {
"_id" = 533cb1c453769a02008c2d55;
name = dddd;
picture = "/img/users/default.jpg";
}
How do I access the above returned JSON, trying to pick apart each returned property to a string or integer etc...
Try this:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = #{#"userName": username, #"password": password};
manager.responseSerializer = [AFJSONResponseSerializer serializer]; // if response JSON format
[manager POST:#"http://asd.com/login.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"%#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#", error);
}];
For parsing the response use this the responseObject as NSDictionary:
NSString *userName = [responseObject objectForKey:#"userName"];
NSString *password = [responseObject objectForKey:#"password"];
Hope this helps.. :)
You may find Send Nested JSON using AFNetworking for the answer.
The error Error Domain=NSCocoaErrorDomain Code=3840 is received invalid JSON object from the server. It is probably caused by the server's improper handling your missing parameters . Your parameters dictionary has only one key object loginName.

Resources