Why does my JSON post request end up as a hex value? - ios

I'm trying to do a post from my iOS app. The JSON I'm trying to pass is called finalConvertedJson and when I print it on the log, it looks like a good JSON object.
But when I post it using the code below, the web service receives the code as a hex value and doesn't know how to handle it. When I try the same JSON object and URL in Postman, it works perfectly.
self.finalStringJson = [[NSString alloc] initWithData:self.finalConvertedJson encoding:NSUTF8StringEncoding];
NSLog(#"this this: %#", self.finalStringJson);
NSData* responseData = nil;
NSString *urlString = #"http://10.2.176.100:9000/TestIOS?mobileData";
NSURL *url=[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
responseData = [NSMutableData data] ;
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
NSString *bodydata=[NSString stringWithFormat:#"%#",self.finalConvertedJson];
[request setHTTPMethod:#"POST"];
NSData *req=[NSData dataWithBytes:[bodydata UTF8String] length:[bodydata length]];
[request setHTTPBody:req];
NSURLResponse* response;
NSError* error = nil;
responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"the final output is:%#",responseString);
I'm guessing it's some sort of encoding issue in my iOS code.
I'm new to iOS so I may be missing something simple here.

I think the problem is on this line...
NSString *bodydata = [NSString stringWithFormat:#"%#",self.finalConvertedJson];
You are using self.finalConvertedJson but I think you intended to use self.finalStringJson. If so, you could just do this...
NSString *bodydata = self.finalStringJson;

Related

Getting Chinese data as UTF8 from web service

I am trying to access a url which is returning some data which has Chinese characters. It returns following response in browser:
{"news":"新聞發佈"}
But when I am trying to read it in my Objective C code I am getting nil in nsdata. Following is my Objective C code:
NSString *final_url = [NSString stringWithFormat:#"http://xx.xxx.xx.xx:xxxx/iph1/NewsAction.do?service=NEWSNOTIF&lang=2&uid=xxxxxxx"];
final_url = [final_url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:final_url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
NSURLResponse *response;
NSError *error = [[NSError alloc] init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *strResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *objectData = [strResponse dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&error];
NSLog(#"json %#",json);
Edit
For testing server guy is sending following data:
String testJson ="新聞發佈";
I there is no error. And data is nil. Then the response form the server itself is not being received. First try by asking the server to send normal string. I think the reason data is nil is not to do with the string encoding here. I suspect the response itself isn't received.

JSON to parse google translate API

I am trying to parse data for google translate. In viewdidload, I wrote the following code.
NSString * target = #"ja";
NSString * source = #"en";
NSString *textEscaped = #"Hi, How are u";
NSString *ke=#"My_key";
NSString * urlText =[NSString
key=%#&source=%#&format=text&target=%#&q=%#",ke,source,target,textEscaped];
NSURL *url = [NSURL URLWithString:urlText];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:url];
[request setHTTPMethod:#"GET"];
NSURLResponse *response;
NSError *error;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response
error:&error];
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#",result);
I compared my code with different sources and my API is also activated but I am getting nothing in result string. Its bill. Why?
Create Your url like this:
[NSString stringWithFormat:#"https://www.googleapis.com/language/translate/v2key=%#&target=%#&q=%#",key, target, selectedWord];

iOS - Extra param in POST request

I am new on iOS development. I try to send POST JSON to my RoR server.
It is my code:
params - some NSDictionary -> { uid = 123 }
NSData *postData = [NSJSONSerialization dataWithJSONObject:params
options:NSJSONWritingPrettyPrinted error:&jsonSerializationError];
NSString *urlString = [[NSString alloc] initWithFormat:#"%#%#", API_URL, url];
NSURL *nsUrl = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:nsUrl];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%lu",
(unsigned long)postData.length] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
At the end in the server I see:
{"uid"=>"123",
"action"=>"mAction",
"controller"=>"mController",
"token"=>{"uid"=>"123"}}
Why I see 'extra token' and how I can remove it ?
there is no reason I can see for the extra "token" to be there, so I would suggest that either the token was in the param all along, or that the receiving script (PHP?) on the server is adding the data someway.
I would suggest you to print the content of parameter with
NSLog(#"param: %#", param);
just to be sure, and also convert the postData to a NSString with something like:
NSString *myString = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
and print that too, just to be on the safe side and, once you have make certain that you aren't sending the "token" parameter, start to debug the receiving end.
Hope this helps
It is a magic problem with a NSDictionary. When I send as NSMutableString - no problems.
NSMutableString *stringData = [[NSMutableString alloc] init];
[params enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
[stringData appendString:[NSString stringWithFormat:#"%#=%#", key, value]];
[stringData appendString:[NSString stringWithFormat:#"&"]];
}];
NSData *postData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
I don't know what happens and why :(

Request-URI Too Large error came [while encoding image using base64 and send to php]

Encoding:
NSData *imageData2 =UIImageJPEGRepresentation(image_emp.image, 0.1);
[Base64 initialize];
NSString *encodedString = [imageData2 base64EncodedStringWithOptions:0];
json:
NSString *posturl=[NSString stringWithFormat:#"http://xxxx.com/image.php?img=%#",encodedString];
//[posturl stringByReplacingOccurrencesOfString:#"+" withString:#"%2B"];
NSString* urlTextEscaped = [posturl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"replace log %#",urlTextEscaped);
[urlTextEscaped stringByReplacingOccurrencesOfString:#"+" withString:#"%2B"];
NSLog(#"the office login url is %#",posturl);
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"%#",urlTextEscaped]];
// NSURL *url=[NSURL URLWithString:[posturl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request=[[NSMutableURLRequest alloc]init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSError *error;
NSURLResponse *response;
NSData *urldata=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urldata encoding:NSUTF8StringEncoding];
NSLog(#"the overall value is %#",data);
NSDictionary *results=[data JSONValue];
NSLog(#"the results:%#",results);
NSArray *value=[results objectForKey:#"message"];
NSLog(#"the array value %#",value);
array value[log]:
Request-URI Too Large
How can I solve this type of issue.Kindly give any ideas.Thanks in Advance.
Don't POST the data in the URL, take advantage of the post body and submit it there. It's the only way to get a lengthy amount of data submitted.

NSURLConnection sends GET request instead of POST request

I'm trying to make a POST request using NSURLConnection. I use Charles to debug and Charles every time says that the method is GET. I've tried all different ways and can't get it to work. I am NOT using JSON.
-(void)getList
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSURL *url = [NSURL URLWithString:#"http://example.com/api/getList"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *radius = #"15";
NSString *latitude = #"-117.820833";
NSString *longitude = #"34.001667";
NSString *parameters = [NSString stringWithFormat:#"longitude=%#&latitude=%#&radius=%#", longitude,latitude, radius];
NSLog(#"PARAMS = %#", parameters);
NSData *data = [parameters dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"text/plain" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:data];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc]initWithData:result encoding:NSUTF8StringEncoding];
NSLog(#"RESULT = %#", responseString);
}
Does anybody know what am I doing wrong? When I access my web service it seems like I'm not posting anything. I'm getting empty response.
Please help with any ideas. I pretty much have to make a simple POST request. Maybe someone can help me debug this better.
If the server is redirecting your request for some reason (perhaps authentication) then the POST information can get lost.

Resources