i am trying to send json array data to server but it show the result is failed.
so plaese correct me where i did wrong.Here is code what i am using in this:
NSDictionary *dict=#{#"groupmembersarray":contactsArray};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *post = [NSString stringWithFormat:#"%#",jsonString];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://anaadit.net/caffe/newapp/AddGroupContact.php"]];
[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];
if(conn==nil) {
NSLog(#"Connection could not be made");
} else {
responseData = [NSMutableData new];
NSLog(#"%#",responseData);
}
and nsurl connection delegate methods calling but the response is showing is nil .
so please check and correct me .Thanks in advance.
Use AFNetworking frame work instead, easy to use and implement.
https://github.com/AFNetworking/AFNetworking
POST request in AFNetworking -
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *dict=#{#"groupmembersarray":contactsArray};
manager.requestSerializer = [AFJSONResponseSerializer serializer];
[manager POST:#"http://anaadit.net/caffe/newapp/AddGroupContact.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
To set ant http header field you can use,
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
Please contact your webservice developer, he/she may have had some issue
Your question has been answered here: How to send POST and GET request?
Although judging from your comment, the issue isn't with the actual request but rather with the server. You wouldn't have gotten a response if your request code was faulty. You should check that the parameters are corresponding with what the server needs.
You can also check the status code of the request like so:
[(NSHTTPURLResponse*)response statusCode]
Related
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 want to convert this code to AFNetworking but i have a error. i used
AFNetworking POST to REST webservice this code.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *latest_url = #"url_string";
[request setURL:[NSURL URLWithString:latest_url]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:useragent_string forHTTPHeaderField:#"User-Agent"];
[request setValue:host_string forHTTPHeaderField:#"Host"];
[request setValue:#"keep-alive" forHTTPHeaderField:#"Connection"];
[request setValue:#"keep-alive" forHTTPHeaderField:#"Proxy-Connection"];
[request setTimeoutInterval:30.0];
[request setHTTPBody:postData];
NSError *errorx = nil;
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&errorx];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSData *jsonData = [json_string dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonerror;
NSData *get_data_from_request = [ourdelegate do_request:request_url post_array:request_post_array debug:istekdebug];
NSArray *statuses =[NSJSONSerialization JSONObjectWithData: jsonData options: NSJSONReadingMutableContainers error: &jsonerror];
How to convert this code to AFNetworking?
Since you are using post request, here's what you can do with AFHTTPSessionManager. You can also call AFHTTPSessionManager Get method with block invocation.
NSURL *baseURL = [NSURL URLWithString:BaseURLString];
NSDictionary *parameters = #{#"Host": host_string};
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:#"yourFile.php" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog("handle succes");
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog("handle error %#",[error localizedDescription]);
}];
Have fun :)
Since you aren't being specific with the error like rckoenes mentioned above.......
Why don't you just go get PAW from LuckyMarmot
It helps you formulate REST api calls and will translate the request into AFNetworking for you. Phenomenal tool for only $19.99. Worth every penny.
I got the following Postman request which works fine (Screenshot http://postimg.org/image/s7zm3qhvh/). But when i try the same in iOS it will not work. Maybe someone can give me some information why.
My Objective-c Code:
UIImage *yourImage= [UIImage imageNamed:#"login-main-bg.png"];
NSString *imageString = [UIImagePNGRepresentation(yourImage) base64Encoding];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
imageString, #"image",
nil];
NSError *error;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
if (error) {
NSLog(#"%#",[error localizedDescription]);
}
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[jsonData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://server.website.net/api/collaboration/ImageTest"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"multipart/form-data" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:jsonData];
//print json:
NSLog(#"JSON summary: %#", [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding]);
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
I hope someone can help me! Thank you!
You're posting a json representation of a base64 encoded string of your image. The postman request is doing a raw binary post with multipart form boundaries.
You want something more like what is shown here https://stackoverflow.com/a/23517227/96683
I am able to get the JSON Response in iOS code through POST Request only when the parameters are empty. Response from Server is { Token = "" }
NSString *postData = [NSString stringWithFormat:#""];
But when I add any parameters like shown below, I get 400 status code as response.
NSString *postData = [NSString stringWithFormat:#"userName=aps#test.com&deviceCode=bhj234&pwd=1234"];
The interesting thing is the same parameters work in REST Client perfectly and gets a response. And also works in Android code too. In android a JSON object is created then these key value pairs are added to the JSON object
JSONObject jsonObj = new JSONObject();
jsonObj.put("userName", "apple#test.com");
jsonObj.put("deviceCode", "Dev455");
jsonObj.put("pwd", "225");
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
httppost.setEntity(entity);
and request and then receives the correct response.
Can anyone suggest me the equivalent code for iOS for the above Android code?
My present code is
NSMutableString *URL=[[NSMutableString alloc] initWithString:#"http://***.***.**.***/Serv.svc/Login"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URL]];
NSString *postData = [NSString stringWithFormat:#"userName=aps#test.com&deviceCode=bhj234&pwd=1234"];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSLog(#"post:%#",postData);
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSLog(#"post:%#",[postData dataUsingEncoding:NSUTF8StringEncoding]);
[request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
User AFNetworking and improt the following in your class
#import "AFNetworking.h"
#import "AFHTTPRequestOperationManager.h"
#import "AFHTTPRequestOperation.h"
Use the following code to for Post request:
- (void)sendPOSTRequest {
NSArray *keys = [NSArray arrayWithObjects:#"userName",#"deviceCode",#"pwd",nil];
NSArray *objects = [NSArray arrayWithObjects:#"apple#test.com",#"Dev455",#"225", nil];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjects:objects forKeys:keys];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
[manager POST:#"yourURL" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError * error = nil;
id json = [NSJSONSerialization JSONObjectWithData:[operation responseData] options:0 error:&error];
NSLog(#"JSON: %#", json);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
In case if everything else doesn't work, try to pass parameters in url:
NSString *URL=[[[NSMutableString alloc] initWithString:#"http://***.***.**.***/Serv.svc/Login?userName=aps#test.com&deviceCode=bhj234&pwd=1234"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URL]];
NSLog(#"post:%#",URL);
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
Once it worked for me, however this of course doesn't answer what is the problem with your code.
I found the answer for my question.
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setValue:#"aps#test.com" forKey:#"userName"];
[dict setValue:#"vikkj107" forKey:#"deviceCode"];
[dict setValue:#"1234" forKey:#"pwd"];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict
options:NSJSONReadingMutableLeaves error:nil];
NSMutableString *URL=[[NSMutableString alloc] initWithString:#"http://***.***.**.***/Serv/Register"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URL]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *resultStr=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
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.