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
Related
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];
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);
}];
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];
I am trying to upload images to Parse.com using AFNetworking 2.0.
When I download the image which has been stored on 'Parse', then the resulting file is corrupt.
By doing a diff I see that the following data has been appended to the beginning:
There is also appended 'boundry' data at the end of the file.
What am I doing wrong? Mime type?
I send the same file using 'curl' and everything is ok.
This is the code I use for sending:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager setResponseSerializer:[AFJSONResponseSerializer serializer]];
[manager.requestSerializer setValue:#"image/jpeg" forHTTPHeaderField:#"Content-Type"];
[headers enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *value, BOOL *stop) {
[manager.requestSerializer setValue:value forHTTPHeaderField:key];
}];
[manager POST:#"https://api.parse.com/1/files/imagefile.jpg"
parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
NSData *imgData = UIImageJPEGRepresentation(image, 1.0f);
[formData appendPartWithFileData:imgData
name:#"imagefile"
fileName:#"imagefile.jpg"
mimeType:#"image/jpeg"];
}
success:^(AFHTTPRequestOperation *operation, id responseObject) {
success(operation, responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
failure(operation, error);
}
];
UPDATE
The following code works as expected (not multi-part, so clearly this is the problematic area):
NSMutableString *urlString = [NSMutableString string];
[urlString appendString:#"https://api.parse.com/1/"];
[urlString appendFormat:#"files/imagefile.jpg"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request addValue:#"***********" forHTTPHeaderField:#"X-Parse-Application-Id"];
[request addValue:#"***********" forHTTPHeaderField:#"X-Parse-REST-API-Key"];
[request addValue:#"image/jpeg" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:UIImageJPEGRepresentation(image, 0.3f)];
NSURLResponse *response = nil;
NSError *error = nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
NSString *fileUrl = [httpResponse allHeaderFields][#"Location"];
How do I replicate this NSURLConnection code in AFNetworking 2.0?
NSString *post = #"key=xxx";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://test.com/"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[conn start];
Short answer: use the AFHTTPRequestSerializer provided by AFNetworking.
According to the document:
[[AFHTTPRequestSerializer serializer] requestWithMethod:#"POST" URLString:URLString parameters:parameters];
sends:
POST http://example.com/
Content-Type: application/x-www-form-urlencoded
foo=bar&baz[]=1&baz[]=2&baz[]=3
If you are using AFHTTPRequestOperationManager:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
// you can use different serializer for response.
manager.responseSerializer = [AFJSONResponseSerializer serializer];
It is given in the AFNetworking page github link
The code for sending post request is below, just import the AFNeworking folder in your project in xocde and add necessary frameworks getting started with afnetworking
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"key": #"xxx"};
[manager POST:#"http://test.com" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
In order to POST form-data with AFNetworking you must create this format out of your NSDictionary:
say you have to send these params :
{
key1 = val1;
key2 = val2;
key3 = val3;
}
create this format and encode data using UTF8Encoding :
key1=val1&key2=val2&key3=val3
You can use this formatting :
NSMutableString *str = [[NSMutableString alloc]init];
NSArray *allKeys = [dict allKeys];
for (NSString *key in allKeys) {
[str appendString:key];
[str appendString:#"="];
[str appendString:[dict valueForKey:key]];
[str appendString:#"&"];
}
[str deleteCharactersInRange:NSMakeRange([str length]-1, 1)];
NSData *requestBodyData = [str dataUsingEncoding:NSUTF8StringEncoding];
AFNetworking creates NSMutableRequest. In the HTTPBody of NSMutableRequest instance pass this requestBodyData.
Done.