Difficulty receiving JSON from GET request using NSURLConnection - ios

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/

Related

Unsupported URL when sending Json value as argument in GET method

Code:
arrValues = [[NSMutableArray alloc]initWithObjects:#"Chennai", nil];
arrKeys = [[NSMutableArray alloc]initWithObjects:#"loc", nil];
dicValue = [NSDictionary dictionaryWithObjects:arrValues forKeys:arrKeys];
NSString *strMethodName = #"agentuserlist";
strUrlName = [NSString stringWithFormat:#"%#%#?filters=%#",appDelegate.strURL, strMethodName, dicValue];
//strUrlName = [strUrlName stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:strUrlName] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:250.0];
[request setHTTPMethod:#"GET"];
[request setHTTPShouldHandleCookies:YES];
[request setValue:#"zyt45HuJ70oPpWl7" forHTTPHeaderField:#"Authorization"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
NSError *error;
NSURLResponse *response;
NSData *received = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:&error];
NSLog(#"error:%#", error);
NSString *strResponse = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];
NSLog(#"response :%#", strResponse);
I try to send json argument through get method.It gives error as "unsupported url(-1002)".
The URL is working fine when I checked with Postman. I am unable to find out the problem.
Where I went wrong?
I think the problem lies in how you encode your NSDictionary in the NSURL.
You probably want your URL to look like this: http://my domain.com/agentuserlist?loc=Chennai. But the raw encoding of the NSDictionary inside the NSURL doesn't produce this result.
You can follow the accepted answer
from this question to get an idea of how to transform an NSDictionary into a regular list of URL parameters (with proper encoding of dictionary values: don't forget the stringByAddingPercentEscapeUsingEncoding part): Creating URL query parameters from NSDictionary objects in ObjectiveC

How can i post json string to server

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.

Format for POST Request in iOS

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];

IOS Json error in sending to http post and setting entity

Hi I am sending an http post request to a server the java code i am referring to has a method as set entity in the post request. How can i achieve this in iOS .
I am presently putting the json data to be sent in the body but am getting the error
Error 500 Cannot read request parameters due Invalid parameter, expected to be a pair
but was
{
"chatMessage" : {
"reportRequest" : "Sent",
"text" : "wdfsds acd"
}
my code is
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:[var.projectUsername base64EncodedString] forHTTPHeaderField:#"Authorization"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPShouldHandleCookies:YES];
NSMutableDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:messageText.text,#"text",#"Sent",#"reportRequest",nil];
NSDictionary *dictionary1 = [NSDictionary dictionaryWithObjectsAndKeys:dictionary,#"chatMessage", nil];
NSError *error = nil;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dictionary1 options:NSJSONWritingPrettyPrinted error:&error];
[request setHTTPBody:jsonData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
Add this in your code:- [request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];

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