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")
Related
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.
I came across a problem with string encoding in ios development. The story is as below:
I create some values in Chinese and then create a NSDictionary for those values, the dictionary is used as parameter for network request:
- (void)createActivity
{
NSString *actionTheme = titleF.text;
NSString *actionTitle = biaotiF.text;
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:actionTheme, #"actionTheme", actionTitle, #"actionTitle",nil];
[self networkrequest:];
}
Then some work has been done for the dictionary:
Transform the dictionary to the form of JSON as the type of NSString.
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
Encoding the string , because of Chinese word in the string.
NSString *urlEncodedString = [jsonString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
At last a full url was create with the string above:
http://app.ic100.com/action/add?paramJson=%7B%22actionTheme%22%3A%22%E6%88%96%E8%80%85%E5%92%8C%E7%94%9F%E6%B4%BB%22%2C%22actionSite%22%3A%22%E5%8E%A (something like this)
I use the third party "ASIFormDataRequest" for network request, and I also set the StringEncoding:
ASIFormDataRequest *requstHttp = [[ASIFormDataRequest alloc] init];
[requstHttp setStringEncoding:NSUTF8StringEncoding];
....
All the datas has been sent to the server successfully, but when I request these data from the server and show then on the iphone. It turn to be unreadable text:
I have carefully checked all the place that I should encode or decode the string, and only utf8 is used. What`s more , for the server side , no other encoding used either. And my colleague has tested sent data from Android platform, no problem. So I think maybe I have missed some points.
Any advise?
By using the class Base64 you can encode or decode the string.
Add Base64 class in your project from HERE
see the mehode in class to encode.
Encode:
+ (NSString *)stringWithBase64EncodedString:(NSString *)string;
- (NSString *)base64EncodedString;
Decode:
- (NSString *)base64DecodedString;
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.
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.
How do we convert a NSDictionary into JSON data object? I want to send a JSON data to my server. I am using the below code but facing an issue when it comes to NSDictionary containing Array or further NSDictionary in it. This works well with simple key-value pair.
Issue: It fails on the below line and sets the error object. This works fine if I remove arrays and dictionaries from the source myData dictionary.
NSData *aPostBodyData = [NSJSONSerialization dataWithJSONObject:myData options:0 error:&error];
Where myData looks like:
{
URI = "www.google.com";
addOnTestString = "4,3,";
status = (
"In Progress",
Submitted,
Delivered
);
data =
{
URI = "www.test.com";
testString = "43";
status = (
"In Progress",
Submitted,
Delivered
);
}
}
Error trace:
ok i just write a sample code that includes your situation and it works well.
NSArray * myarray=#[#"a",#"b"];
NSMutableDictionary * dict=[[NSMutableDictionary alloc] initWithObjects:#[#"a",myarray] forKeys:#[#"str",#"arr" ]];
NSData * js=[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
NSString * jsString=[[NSString alloc] initWithData:js encoding:NSUTF8StringEncoding];
NSLog(#"%#",jsString);
probable reasons for you get errors may be;
your myData is not in type NSDictionary or NSArray.
or while adding arrays to dictionary you are missing a point.