How can I do a POST call to my api with JSONHTTPClient? - ios

I'm using JSONHTTPClient library from github in my Objective c application. I have a lot of calls to my api and all works, but when I try add a POST function with headers and body, I get an error:
Error Domain=JSONModelErrorDomain Code=2 "Bad network response.
Probably the JSON URL is unreachable."
UserInfo={NSLocalizedDescription=Bad network response. Probably the
JSON URL is unreachable.}
I use the JSONFromURLWithString url to do a POST call. The api call works correctly, returning the data from server (I'm tested this from postman) But from this function in my objective c application I'm getting always error, why not get the response?
Am I sendind any data in bad format?
This is my code:
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:#"var1", #"keyVar1", #"5" , #"keyvar2", nil];//Here initialize my headers values into a dictionary
NSDictionary *dicty = [NSDictionary dictionaryWithObjectsAndKeys:#"6234", #"id", #"4324" , #"id2", nil];//This is my body
NSData *jsonDatass = [NSJSONSerialization dataWithJSONObject:dicty options:0 error:nil];//Here convert my body to nsdata
[JSONHTTPClient JSONFromURLWithString:#"myURL" method:#"POST" params:nil orBodyData:jsonData headers:parameters completion:^(id json, JSONModelError *err){
NSLog(#"have error?: %#", err);
NSLog(#"have response?: %#", json);
}];

I think for pass json in url first you need to convert json in to the string and then pass then string as a argument. Thats why in postman it works well.
I want to know the complete URL after you joining together,in the
[JSONHTTPClient JSONFromURLWithString:#"myURL" method:#"POST" params:nil
orBodyData:jsonData headers:parameters completion:^(id json, JSONModelError *err){
}
method,your complete URL shoud be same as
******************************** divider ***********************************
NSString *myString = [[NSString alloc] initWithData:jsonDatass encoding:NSUTF8StringEncoding];
myString = [myString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *uploadUrl = [NSString stringWithFormat:#"<YOU host URL>"?data=%#",myString];
also parameters Should be converted to string to splice into the url.

Related

Why is NSJSONSerialization parsing NSDictionary incorrectly into JSON?

I'm making a POST request to a server from an IOS app and sending a JSON payload of an email and password value.
My code so far is making a NSDictionary and serializing it into NSData:
NSDictionary *dictionary = #{ #"email" : #"khush#gmail.com" , #"password" : #"mypass" };
NSData *payload = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:nil];
I attach the payload as part of the request.HTTPBody, however the server receives the following data:
{ '{"email":"khush#gmail.com", "password":"mypass"}' : ' ' }
It seems to be taking the whole string as the key and emitting a null as the value.
Any ideas/solutions to this problem? I've had a look at but it doesn't make See this link sense to me.
Nothing is wrong in your payload. Data is being messed up in HTTP layer. Please ensure you have following content type set in your request headers.
"Content-Type" = "application/json";
Seems like you are making something like
request.HTTPBody = encodedVersionOfPayload;
while you should be marking something more like
request.HTTPBody = [NSString stringWithFormat:#"%#=%#", yourKey, encodedVersionOfPayload];
Please show us this part of your code.
UPDATE
After a quick look to documentation, NSMutableURLRequest, HTTPBody property is a NSData and not a NSString,
so you have probably written
request.HTTPBody = payload;
where you should have something more like
NSString *jsonString = [[NSString alloc] initWithData:payload encoding:NSUTF8StringEncoding];
NSString *payloadString = [NSString stringWithFormat:#"data=%#", jsonString];
request.HTTPBody = [payloadString dataUsingEncoding:NSUTF8StringEncoding];
(not tested but should be correct, your json object should be available on your server using the key "data")

How do I urlencode this NSString that contains a JSON inside it?

I have the following json string that should be sent to the backend
{
id = "MU_200255802";
keywords = (
Talk,
games,
meetup,
time,
meet,
"Time for Another Game"
);
}
So before this JSON I have the java servlet URL something like
http://....net/servletName?
How should I urlencode the json string and the url because even after trying several options, I keep getting bad url as an error back in the delegate method. What is the right way to do it/
I tried encoding using
NSString *urlStringEncoded = [[NSString stringWithString:urlString] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
and also used other encoding formats too.
Use this to create json string
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:#"Your object" options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
You can use Google Toolbox for Mac, check it out here, https://code.google.com/p/google-toolbox-for-mac/source/checkout
There are Classes named GTMNSString+HTML,GTMNSString+XML,GTMNSString+URLArguments, which contains many encoding methods for you.

reading a json object from a website in objective c

I need to separate sub person, name, age, home addr, office addr from below given json object retrieved from a website
{ "person" :
[{"subperson":{"home":{"id":"kljljk"},"name":"person3","age":"18","addr":{"home addr":"ksdjr","office addr":"kjshdg"}}}]}
tried nsjsonserialization,sbjson and touchJSON api's. returns a dictionary in which person is the key and everything else is the value(format of json string specified below the code)
my code:
NSURLRequest *urlreq = [NSURLRequest requestWithURL:url];
NSData *response = [NSURLConnection sendSynchronousRequest:urlreq returningResponse:nil error:nil];
[webviv loadRequest:urlreq];
SBJsonParser *jsonparser = [SBJsonParser new];
NSDictionary *json = [jsonparser objectWithData:response];
NSLog(#"%#\n", json);
for(id key in json)
{
NSLog(#"%#=%#",key,[json objectWithKey: key]);
}
//output is
person = (everythingelse starting with [, can't separate name and other required things)
//using NSJSONSerialization
if ([NSJSONSerialization JSONObjectWithData:response options:0 error:&error])
{
NSLog(#"json");
}
NSData *pTL = [NSJSONSerialization JSONObjectWithData:response options:0 error:&error];
NSLog(#"%#",pTL);
//Output is the same
//for(int i=0;i<[pTL count];i++)
//{
//NSLog(#"%d",i);
//}
//even with for loop the output is the same
Tell your backend guys(the person who wrote this web service) to change "[" as "(" and "]" as")". ( is array { is dictionary. [ is nothing for us we can differentiate it
There is a problem with your JSON structure.
For instance, the following is not a legal JSON string:
"subperson":"home":{"id":"kljljk"}
Try replacing it with the following:
{"person":[{"subperson":{"id":"kljljk","name":"person3","age":"18","addr":{"homeaddr":"ksdjr","office addr":"kjshdg"}}}]}
You can use any kind of online JSON parser tool to verify the JSON structure before continuing to debug your code.
Also you should read a little about JSON syntax here.

Encode JSON data for URL

In iOS, I want to send JSON data in URL to make service call. I tried following code snipped but Encoded URL seems wrong. Because in JSON there is a colon character (:) between key and value and comma character (,) for separation. But, i am not able to encode colon(:) as %3A and comma(,) as %2C
Code Snippet:
- (NSURL *)getEncodedUrl {
// Build dictionnary with parameters
NSString *abc = #"abc";
NSNumber *limitNumber = [NSNumber numberWithInt:2];
NSMutableDictionary *dictionnary = [NSMutableDictionary dictionary];
[dictionnary setObject:limitNumber forKey:#"limit"];
[dictionnary setObject:abc forKey:#"abc"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionnary options:0 error:&error];
if (!jsonData) {
debug("Json error %#",error);
return nil;
} else {
NSString *JSONString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
debug("Json op %#",JSONString);
NSString* params = [JSONString stringByAddingPercentEscapesUsingEncoding:
NSASCIIStringEncoding];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://baseUrl.com?param=#",params]];
debug("URL = %#",url);
return url;
}
}
OUTPUT:~
URL = http://baseUrl.com?param=%7B%22abc%22:%22abc%22,%22limit%22:2%7D
(Include colon and comma characters)
But I want following o/p:
http://baseUrl.com?param=%7B%22abc%22%3A%22abc%22%2C%22limit%22%3A2%7D
(No colon and comma characters)
Online Encoding-Decoding Site that I am referring as of now.
http://www.url-encode-decode.com/
you can simply use
NSString *url = #"http://baseUrl.com?param=%7B%22abc%22:%22abc%22,%22limit%22:2%7D";
NSString *encodeImgUrl = [url stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
I'd recommend that you send the JSON as POST data instead of the GET that you're using. It'd be more straightforward to package it as MIME data and any encoding you do would be easier to understand.
So you are trying to generate the query portion of a URL here. Colons are a perfectly legitimate character to include in URL queries. I wrote an article covering the intricacies of escaping URL queries in Cocoa:
http://www.mikeabdullah.net/escaping-url-queries-in-cocoa.html
Since you're keen to perform extra escaping, I suggest taking my sample code and extending it to specially ask for : and ; characters to be escaped too.
I made small mistake in API call that is why I am getting wrong result. There is no need to encode colon(:) as %3A and comma(,) as %2C.
One more thing I would like to share with you. You can use base64 string instead of encoding JSON part.

NSData to NSString with JSON response

NSData* jsonData is the http response contains JSON data.
NSString* jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"jsonString: %#", jsonString);
I got the result:
{ "result": "\u8aaa" }
What is the proper way to encoding the data to the correct string, not unicode string like "\uxxxx"?
If you convert the JSON data
{ "result" : "\u8aaa" }
to a NSDictionary (e.g. using NSJSONSerialization) and print the dictionary
NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"%#", jsonDict);
then you will get the output
{
result = "\U8aaa";
}
The reason is that the description method of NSDictionary uses "\Unnnn" escape sequences
for all non-ASCII characters. But that is only for display in the console, the dictionary is correct!
If you print the value of the key
NSLog(#"%#", [jsonDict objectForKey:#"result"]);
then you will get the expected output
說
I don't quite understand what the problem is. AFNetworking has given you a valid JSON packet. If you want the above code to output the character instead of the \u… escape sequence, you should coax the server feeding you the result to change its output. But this shouldn't be necessary. What you most likely want to do next is run it through a JSON deserializer…
NSDictionary * data = [NSJSONSerialization JSONObjectWithData:jsonData …];
…and you should get the following dictionary back: #{#"result":#"說"}. Note that the result key holds a string with a single character, which I'm guessing is what you want.
BTW: In future, I suggest you copy-paste output into your question rather than transcribing it by hand. It'll avoid several needless rounds of corrections and confusion.

Resources