How can i post json string to server - ios

This is json string that I have to post...
{
"data": {
"description": "",
"current_value": "",
"serialno": "",
"condition": "",
"category": "category",
"purchase_value": "",
"new_or_used": "",
"gift_or_purchase": "",
"image": ""
},
"subtype": "fd3102d8-bc19-424b-bca2-774a8fd7ea6f"
}
How to post as JSON?

Surely this Q us a duplicate, but here's full example code, as one long routine. Just copy and paste.
First set up the JSON...
-(void)sendTestJsonCommand
{
NSMutableDictionary *dict = #{
#"heights":#"4_5_7",
#"score":#"4",
#"title":#"Some Title",
#"textBody":#"Some Long Text",
#"happy":#"y"
}.mutableCopy;
NSError *serr;
NSData *jsonData = [NSJSONSerialization
dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&serr];
if (serr)
{
NSLog(#"Error generating json data for send dictionary...");
NSLog(#"Error (%#), error: %#", dict, serr);
return;
}
NSLog(#"Successfully generated JSON for send dictionary");
NSLog(#"now sending this dictionary...\n%#\n\n\n", dict);
Next, correctly asynchronously send the command and json to your server...
#define appService [NSURL \
URLWithString:#"http://www.corp.com/apps/function/user/pass/id/etc"]
// Create request object
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:appService];
// Set method, body & content-type
request.HTTPMethod = #"POST";
request.HTTPBody = jsonData;
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:
[NSString stringWithFormat:#"%lu",
(unsigned long)[jsonData length]] forHTTPHeaderField:#"Content-Length"];
// you would almost certainly use MBProgressHUD at this point
// to display some sort of spinner or similar action on the UX
Finally, (A) connect correctly using NSURLConnection, and (B) correctly interpret the information which comes back to you from your server.
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *r, NSData *data, NSError *error)
{
if (!data)
{
NSLog(#"No data returned from server, error ocurred: %#", error);
NSString *userErrorText = [NSString stringWithFormat:
#"Error communicating with server: %#", error.localizedDescription]
return;
}
NSLog(#"got the NSData fine. here it is...\n%#\n", data);
NSLog(#"next step, deserialising");
NSError *deserr;
NSDictionary *responseDict = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&deserr];
NSLog(#"so, here's the responseDict\n\n\n%#\n\n\n", responseDict);
// LOOK at that output on your console to learn how to parse it.
// to get individual values example blah = responseDict[#"fieldName"];
}];
}
Hope it saves someone some typing!

Use following shnchronous request, you can use asynchronous request as well,
NSError *error;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:<Your API URL>]];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:<Your Mutable NSDictionary> options:NSJSONReadingMutableContainers error:&error];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:jsonData];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//NSLog(#"results string = %#",[[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]);
NSDictionary *temp= [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil];// This will convert Data to Json format

As per my point of view you can Use NSURLSeession with Asyn request (Try to implement NSURLSession)
NSData *postData =[NSJSONSerialization dataWithJSONObject:Data options:0 error:&error];
if (!error)
{
NSString *urlpart = [NSString stringWithFormat:#“Your URL];
NSURL *requestUrl = [NSURL URLWithString:urlpart];
NSMutableURLRequest *URLRequest = [NSMutableURLRequest requestWithURL:requestUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
URLRequest.allowsCellularAccess=YES;
[URLRequest setHTTPMethod:#"POST"];
[URLRequest setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[URLRequest setHTTPBody:postData];
WebServiceManager *webserviceManager = [[WebServiceManager alloc] init];// this is your comman class for webServices connections
[webserviceManager sendRequest:URLRequest withOwner:self successAction:#selector(delegateMethod:) failAction:#selector(Error:)];
}

Replace:
NSData *postData = [jsonString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
With:
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:jsonString options:0 error:&error];
An object that may be converted to JSON must have the following properties:
The top level object is an NSArray or NSDictionary.
All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.
All dictionary keys are instances of NSString.
Numbers are not NaN or infinity.

Related

Difficulty receiving JSON from GET request using NSURLConnection

I'm having a hard time trying to receive JSON form a NSURLConnection request. Can anybody offer any advice? I can't understand why the JSON does not appear
EDIT: When I append the endpoint /books to the end of the url string I get this JSON response: " json NSDictionary * 0 key/value pairs. " Does this mean that there is nothing in the server?
-(void)makeLibraryRequests
{
NSURL *url = [NSURL URLWithString:#"http://prolific-interview.herokuapp.com/54bexxxxxxxxxxxxxxxxaa56"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; //;]cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0f];
[request setHTTPMethod:#"GET"];
// This is actually how jQuery works. If you don't tell it what to do with the result, it uses the Content-type to detect what to do with it.
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
//[request setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//parse data here!!
NSError *jsonError;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
if (json) {
//NSArray *allBooks = [json objectForKey:#"books"];
//create your MutableArray here
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}
else{
NSLog(#"error occured %#", jsonError);
NSString *serverResponse = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"\n\nError:\n%#\n\nServer Response:\n%#\n\nCrash:", jsonError.description, serverResponse);
//[NSException raise:#"Invalid Data" format:#"Unable to process web server response."];
}
}];
}
As YiPing pointed out, you must provide the books end point. But you won't have anything there until you first post a book.
NSDictionary *params = #{#"author": #"Diego Torres Milano",
#"categories" : #"android,testing",
#"title": #"Android Application Testing Guide",
#"publisher": #"Packt Publishing",
#"lastCheckedOutBy": #"Joe"};
NSURL *url = [NSURL URLWithString:#"http://prolific-interview.herokuapp.com/54bexxxxxxxxxxxxxaa56/books/"]; // your id removed for security's sake ... put it back in
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSError *encodeError;
NSData *body = [NSJSONSerialization dataWithJSONObject:params options:0 error:&encodeError];
NSAssert(body, #"JSON encode failed: %#", encodeError);
request.HTTPBody = body;
So, first POST a book using a request like the above, then your original GET (assuming you add the end point) will now return a result.
Add some endpoints to your URL
try this:
http://prolific-interview.herokuapp.com/54bexxxxxxxxxxxxxxxxaa56/books/

unable to get response from web service where my url works good in browser

i am using this url "http://test.ccsplinfo.com/services.svc/addSubscriber?userdetails={Email_Id:mishra.bn#gmail.com,FirstName:BN,LastName:MISHRA,MobileNumber:8285547554,Password:mypass}" to get data from server. But i am not getting any response. when i am just copy and paste
this url to browser then getting true response.it means url working good but i am getting mistake in my code my code is here..
NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
[dict setObject:#"mishra.bn#gmail.com" forKey:#"Email_Id"];
[dict setObject:#"BN" forKey:#"FirstName"];
[dict setObject:#"MISHRA" forKey:#"LastName"];
[dict setObject:#"8285547554" forKey:#"MobileNumber"];
[dict setObject:#"mypass" forKey:#"Password"];
NSString *PostUrl=#"http://test.ccsplinfo.com/services.svc/addSubscriber?userdetails=";
NSError *serr;
NSData *jsonData = [NSJSONSerialization
dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&serr];
if (serr)
{
NSLog(#"Error generating json data for send dictionary...");
NSLog(#"Error (%#), error: %#", dict, serr);
return;
}
// Create request object
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:PostUrl]];
request.HTTPMethod = #"POST";
request.HTTPBody = jsonData;
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:
[NSString stringWithFormat:#"%lu",
(unsigned long)[jsonData length]] forHTTPHeaderField:#"Content-Length"];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *r, NSData *data, NSError *error)
{
if (!data)
{
NSLog(#"No data returned from server, error ocurred: %#", error);
NSString *userErrorText = [NSString stringWithFormat:
#"Error communicating with server: %#", error.localizedDescription];
return;
}
NSError *deserr;
NSDictionary *responseDict = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&deserr];
NSLog(#" responseDict :%#", responseDict);
}];
Thanks
Your request look fine. I think you would be getting below error
Error Domain=NSCocoaErrorDomain Code=3840
JSON text did not start with array or object and option to allow fragments not set.
It's because server is responding with invalid JSON object.

HTTP request GET response showing NULL value

I want to create HTTP request post and get response by using simple Objective C Code method. Here below code to I can post successfully. But I didn't receive response data's. Response printing null value only. Please help me, I need to get response data's.
Here below my code
NSString *post = [NSString stringWithFormat:#"name=%#",name];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:URLPATH]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn) {
NSLog(#"Connection Successful");
} else {
NSLog(#"Connection could not be made");
}
// Create GET method
NSError *err;
NSURLResponse *responser;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responser error:&err];
// JSON Formatter
NSError *error;
NSDictionary *jsonsDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSDictionary *respon = [jsonsDictionary objectForKey:#"response"];
NSLog(#"UPDATE RESPONSE : %#", respon);
You's data post is NSString *post = [NSString stringWithFormat:#"name=%#",name]; . So in this case you need set request header "Content-Type" to "application/x-www-form-urlencoded" or use following code to convert string to data and set Content-Type header:
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
...
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
Its very simple:
//-- Convert string into URL
NSString *jsonUrlString = [NSString stringWithFormat:#"demo.com/your_server_db_name/service/link"];
NSURL *url = [NSURL URLWithString:[jsonUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//-- Send request to server
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
//-- Send username & password for url authorization
[request setValue: jsonUrlString forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"]; //-- Request method GET/POST
//-- Receive response from server
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//-- JSON Parsing with response data
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
NSLog(#"Result = %#",result);
Sample : https://github.com/svmrajesh/Json-Sample

Proper JSON encoding for HTTP POST request in iOS

Posted a query previously about JSON parsing not working properly. Did more looking into it with a packet sniffer and also with another client that works properly and found out it's a syntax thing, that I still can't seem to solve.
The code in the bottom makes the HTTP request to have the JSON in it as:
{"key":"value"}
And my server is actually looking for a JSON in the following syntax:
key=%22value%22
I tried to write some code that does this manually, but figured there must be something out of the box for iOS, and I don't want to have faults in the future.
I messed around with it for a while trying to find the right code for the job, but couldn't (you can see some code I tried commented out). Can anyone help me?
+ (NSString*)makePostCall:(NSString*)urlSuffix
keys:(NSArray*)keys
objects:(NSArray*)objects{
NSDictionary *params = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
// NSString *dataString = [self getDataStringFromDictionary:params];
// NSData *jsonData = [dataString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params
options:0
error:&error];
// id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
// NSLog(#"%#", jsonObject);
if (!jsonData) {
// should not happen
NSError *error;
NSLog(#"Got an error parsing the parameters: %#", error);
return nil;
} else {
// NSString *jsonRequest = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// NSLog(#"%#", jsonRequest);
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#", urlPrefix, urlSuffix]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];
// NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
// [request setValue:#"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: jsonData];
NSURLResponse * response = nil;
NSError * error = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
// TODO: handle error somehow
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return returnString;
}
}

How to reach members of json with iOS

I want to reach from ios to a .net .asmx web service, and I reach with the following code:
NSString *urlString = #"http://www.****.com/Mobile.asmx/HelloWorld";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod: #"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned)
{
//...handle the error
}
else
{
NSString *retVal = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#", retVal);
//...do something with the returned value
}
It returns clean json {"hellom":"Hello World","hellom2":"HelloWorld2"} but I can't reach members and value one by one
How can I do that?
You can convert JSON data into an object by using the following code...
NSData *jsonData = ... the data you got from the server
NSDictionary *object = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
object will then be a NSDictionary like this...
#{
hellom : #"Hello World",
hellom2: #"HelloWorld2"
}
You can then get to the keys and values like any other dictionary.

Resources