Error 404 for POST Request using AFNetworking - ios

I'm getting this error and I can't figure out why :/
2015-02-19 10:53:45.005 Agendize[4233:60b] Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: not found (404)" UserInfo=0x1782e4980 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x17022e3c0> { URL: https://mylink } { status code: 404, headers {
Connection = "keep-alive";
"Content-Length" = 104;
Date = "Thu, 19 Feb 2015 16:12:32 GMT";
Server = "nginx/1.1.19";
Here is my xcode request :
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parametersDictionary options:NSJSONWritingPrettyPrinted error:&error];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
[request setHTTPMethod:#"POST"];
[request setValue:#"Basic: someValue" forHTTPHeaderField:#"Authorization"];
[request setValue: #"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
Help please !!!

NSError *error=nil;
NSString *url = #"Your URL to post data";
NSData *jsonRequestDict= [NSJSONSerialization dataWithJSONObject:userDict options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonCommand=[[NSString alloc] initWithData:jsonRequestDict encoding:NSUTF8StringEncoding];
NSLog(#"***jsonCommand***%#",jsonCommand);
NSDictionary *params =[NSDictionary dictionaryWithObjectsAndKeys:jsonCommand,#"requestParam", nil];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer]; //AFHTTPResponseSerializer serializer
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
[manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError *error=nil;
NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"Request Successful, response '%#'", responseStr);
NSMutableDictionary *jsonResponseDict= [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error];
NSLog(#"Response Dictionary:: %#",jsonResponseDict);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];

Related

Json Code is not working

NSString *urlString = #"http://chkdin.com/dev/api/peoplearoundmexy/?";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *parameterString=[NSString stringWithFormat:#"skey=%#&user_id=%#",#"XXXXXXX",#"3225"];
NSLog(#"%#",parameterString);
[request setHTTPMethod:#"POST"];
[request setURL:url];
[request setValue:parameterString forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSData *postData = [parameterString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:postData];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
NSLog(#"%#",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]);
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"%#",dict);
This is my json parsing, my problem is when I am hit this api it is showing
{
message = "Valid skey required.";
status = 0;
}
But this api is working in safari.i am think is the problem is for request adding to url wrong. can you help me please....
i got response through AFNetworking 3
try this
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager GET:#"http://chkdin.com/dev/api/peoplearoundmexy/?" parameters:#{#"skey":#"sa6rw9er7twefc9a7dvcxcheckedin",#"user_id":#"3225"} progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"%#",responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
}];
i tried following code without AFNetworking and its working fine.
NSString *post = [NSString stringWithFormat:#"skey=%#&user_id=%#",#"sa6rw9er7twefc9a7dvcxcheckedin",#"3225"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://chkdin.com/dev/api/peoplearoundmexy/?%#",post]]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:nil];
NSError *error;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
NSLog(#"%#",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]);
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"%#",dict);

send JSON object in POST request AFNetworking , iOS

I'm using AFNetworking to post data into the web. The information I have is the URI which is baseURL/post_user_info and they want input as A JSON object containing each of the name-value pairs. In the code written below I've set the name-value pair in a dictionary. My question is how to make it's json and send it as input value?
NSString *string = [NSString stringWithFormat:#"%#?post_user_info",BaseURLString];
NSString *escapedPath = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *params = #{#"input_1": #"hello world",
#"input_2": #"my#you.com",
#"input_3": #"newworldorder"};
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:params options:kNilOptions error:nil];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:jsonData];
[manager POST:escapedPath parameters:[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] progress:nil success:^(NSURLSessionTask *task, id responseObject)
{
NSLog(#"%#",responseObject);
}failure:^(NSURLSessionTask *operation, NSError *error)
{
NSLog(#"%#",[error localizedDescription]);
}];
I've updated the code because now I have generated the JSON but if I run the code now it give me Error: 400 which means If input_values is empty, a bad request error will be output.
#interface AFJSONRequestSerializer : AFHTTPRequestSerializer
AFJSONRequestSerializeris a subclass ofAFHTTPRequestSerializerthat encodes parameters as JSON using NSJSONSerialization.
add this AFJSONRequestSerializer is used for send JSON not a Raw Data add this and try once
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
e.g
NSString *string = [NSString stringWithFormat:#"%#?post_user_info",BaseURLString];
NSString *escapedPath = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
/************** karthik Code added ******************/
AFHTTPSessionManager* manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
/************** karthik Code added ******************/
NSDictionary *params = #{#"1": #"hello world",
#"2": #"my#you.com",
#"3": #"newworldorder"};
[manager POST:escapedPath parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject)
{
NSLog(#"%#",responseObject);
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
NSLog(#"json == %#", json);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"%#", [error localizedDescription]);
}];
Update Params
NSDictionary *params = #{#"1": #"hello world",
#"2": #"my#you.com",
#"3": #"newworldorder"};
NSMutableDictionary *modify = [NSMutableDictionary new];
[modify setObject:params forKey:#"input_values"];
you get output of

How send json on body by http post request?

I tried to send a json on my server on body via http post method i use Afnetworking but it isn't it response error it it server side problem or http post request problrm
NSDictionary *parameters = #{
#"username": #"hasanProj",
#"password" : #"123321",
#"email" : #"17.chayon#gmail.com",
#"firstName":#"chayon",
#"lastName":#"ahmed"
};
NSData *data = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonStr = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(#"%#",jsonStr);
NSLog(#"%#",parameters);
NSString *urlString = [NSString stringWithFormat:#"http://testgcride.com:8081/v1/users"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
//NSString *jsonString = [self getJSONStringWithDictionary:parameters];
[request setHTTPBody:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];
AFHTTPRequestOperationManager *manager= [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:#"moinsam" password:#"cheese"];
//manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer.acceptableStatusCodes = [NSIndexSet indexSetWithIndex:400];
[manager POST:#"http://testgcride.com:8081/v1/users" parameters:jsonStr success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
Any help is greatly appreciated. Thanks

Basic auth header from username and password is not working In AFNetworking 2.0

I am invoking A API its required Authorisation header.
this is API need on given URL
username : testingyouonit#gmail.com
password : testingyouonit2
to create the Authorisation header
step 1 - do a base64 encoding of the given password.
step 2 - do a SHA256 hash on the password obtained in step 1
step 3 - use the password obtained in step 2 and given username to create the authorization header
Now i am passing request using AFNetworking
NSString *email=#"testingyouonit#gmail.com";
NSString *password=[self encodeStringTo64:#"testingyouonit2"];
Here i encoded my password
- (NSString*)encodeStringTo64:(NSString*)fromString
{
NSData *plainData = [fromString dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String;
if ([plainData respondsToSelector:#selector(base64EncodedStringWithOptions:)]) {
base64String = [plainData base64EncodedStringWithOptions:kNilOptions];
} else {
base64String = [plainData base64Encoding];
}
return base64String;
}
Now i am passing GET Request
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:email password:password];
[manager.requestSerializer setValue:#"CAS256" forHTTPHeaderField:#"Authorization"];
[manager GET:#"https://myurlhere/youit" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
Now each time i am getting this
Error: Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: bad request (400)" UserInfo=0x7c361610 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x7aed9220> { URL: https://myurlhere/youit } { status code: 400, headers {
"Access-Control-Allow-Origin" = "*";
Connection = "keep-alive";
"Content-Length" = 114;
"Content-Type" = "application/json";
Date = "Sat, 11 Jul 2015 02:56:46 GMT";
Server = "nginx/1.1.19";
} }, NSErrorFailingURLKey=https://myurlhere/youit, NSLocalizedDescription=Request failed: bad request (400), com.alamofire.serialization.response.error.data=<7b0a2020 22657272 6f725f63 6f646522 3a202269 6e76616c 69645f61 7574685f 68656164 6572222c 0a202022 6d657373 61676522 3a202249 6e76616c 69642061 7574686f 72697a61 74696f6e 2e205573 6520616e 20617574 68206865 61646572 206f7220 61636365 73732068 61736822 0a7d>}
where is the mistake i am doing to make basic Auth
Lets create SHA256 and pass it password and try it
NSString *email=#"testingyouonit#gmail.com";
NSString *password=[self encodeStringTo64:#"testingyouonit2"];
add one more method to generate a Sha256 password and pass in to request
Step-1 using this method you need to #include <CommonCrypto/CommonDigest.h>
-(NSString*)sha256HashFor:(NSString*)input
{
const char* str = [input UTF8String];
unsigned char result[CC_SHA256_DIGEST_LENGTH];
CC_SHA256(str, strlen(str), result);
NSMutableString *ret = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH*2];
for(int i = 0; i<CC_SHA256_DIGEST_LENGTH; i++)
{
[ret appendFormat:#"%02x",result[i]];
}
return ret;
}
and call this
Note : pass here encoded password you used
NSString *password=[self encodeStringTo64:#"testingyouonit2"];
`password=[self sha256HashFor: password];`
and final step
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:email password:password];
[manager GET:#"https://myurlhere/youit" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
let me see the result
You aren't constructing the header correctly. See the "client side" section here.
Incidentally, you are getting an error 400 which means your request is bad. If it was a security issue, you would be getting a 401. So, fix the Authorization header, but look further for the problem with your request.
try below code
NSString *URLString = #"url";
NSData *data = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonStr = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSString *username = [[NSUserDefaults standardUserDefaults] objectForKey:#"userName"];
NSString *password = [[NSUserDefaults standardUserDefaults] objectForKey:#"password"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSURLCredential *credential = [NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceNone];
NSString *authenticationString = [NSString stringWithFormat:#"%#:%#", username, password];
NSData *authenticationData = [authenticationString dataUsingEncoding:NSASCIIStringEncoding];
NSString *authenticationValue = [authenticationData base64EncodedStringWithOptions:0];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URLString] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0f];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:[NSString stringWithFormat:#"Basic %#", authenticationValue] forHTTPHeaderField:#"Authorization"];
[theRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[theRequest setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[theRequest setHTTPBody:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:theRequest];
[operation setCredential:credential];
[operation setResponseSerializer:[AFJSONResponseSerializer alloc]];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure: %#", error);
}];
[manager.operationQueue addOperation:operation];
For people using AFNetworking 3.x here is full solution that worked for me.
This code sends file with basic authentication. Just change url, email and password.
NSString *serverUrl = [NSString stringWithFormat:#"http://www.yoursite.com/uploadlink", profile.host];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:#"POST" URLString:serverUrl parameters:nil error:nil];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
// Forming string with credentials 'myusername:mypassword'
NSString *authStr = [NSString stringWithFormat:#"%#:%#", email, emailPassword];
// Getting data from it
NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
// Encoding data with base64 and converting back to NSString
NSString* authStrData = [[NSString alloc] initWithData:[authData base64EncodedDataWithOptions:NSDataBase64EncodingEndLineWithLineFeed] encoding:NSASCIIStringEncoding];
// Forming Basic Authorization string Header
NSString *authValue = [NSString stringWithFormat:#"Basic %#", authStrData];
// Assigning it to request
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSURL *filePath = [NSURL fileURLWithPath:[url path]];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
dispatch_async(dispatch_get_main_queue(), ^{
//Update the progress view
LLog(#"progres increase... %# , fraction: %f", uploadProgress.debugDescription, uploadProgress.fractionCompleted);
});
} completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"Success: %# %#", response, responseObject);
}
}];
[uploadTask resume];

POST request with JSON body AFNetworking 2.0

Is there anyway to send a POST request with a JSON body using AFNetworking ~> 2.0?
I have tried using:
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager POST:<url> parameters: #{#"data":#"value"} success: <block> failure: <block>'
but it doesn't work. Any help is greatly appreciated.
Thanks
You can add your JSON body in NSMutableURLRequest not direct in parameters:. See my sample code :
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// Set post method
[request setHTTPMethod:#"POST"];
// Set header to accept JSON request
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// Your params
NSDictionary *params = #{#"data":#"value"};
// Change your 'params' dictionary to JSON string to set it into HTTP
// body. Dictionary type will be not understanding by request.
NSString *jsonString = [self getJSONStringWithDictionary:params];
// And finally, add it to HTTP body and job done.
[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:<block> failure:<block>];
Hope this will help you. Happy coding! :)
If someone looking for AFNetworking 3.0, here is code
NSError *writeError = nil;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:&writeError];
NSString* jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:120];
[request setHTTPMethod:#"POST"];
[request setValue: #"application/json; encoding=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setValue: #"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody: [jsonString dataUsingEncoding:NSUTF8StringEncoding]];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
NSLog(#"Reply JSON: %#", responseObject);
if ([responseObject isKindOfClass:[NSDictionary class]]) {
//blah blah
}
} else {
NSLog(#"Error: %#", error);
NSLog(#"Response: %#",response);
NSLog(#"Response Object: %#",responseObject);
}
}] resume];

Resources