How to Post xml within Json object in NSURLConnection? - iphone

Hi I want to post XML data within JSON Object.
This is the way i post
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
NSString *postString = [NSString stringWithFormat:#"{\"UserId\":\"%#\",\"UserDataXML\":\"%#\"}",#"USRfa9210bad85165d5",#"<Root Bookmark=\"Page1\">\\u000d\\u000a <Name>MyName<\Name>\\u000d\\u000a <Address>MyAddress<\ Address></Root>"];
NSData *requestData = [postString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:requestData];
In connectionDidFinishLoading _responseData is come,But responsedict is getting Null.
Where i am going wrong?
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"_responseData %#",_responseData);
NSString *responseString = [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
NSError *error;
NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"responseDict %#",responseDict);
}

First of all, you must escape your JSON before use.
And then,
(1) If the server is only responding with a form-data, a post data must be a pair of key and value.
NSString *postString = [NSString stringWithFormat:#"UserId=%#&UserDataXML=%#",
#"USRfa9210bad85165d5",
#"<Root Bookmark=\\\"Page1\\\">\\u000d\\u000a<Name>MyName</Name>\\u000d\\u000a<Address>MyAddress</Address></Root>"];
(2) If the server is only responding with JSON, Content-Type should be set to "application/json" and then,
NSString *postString = [NSString stringWithFormat:#"{\"UserId\":\"%#\", \"UserDataXML\":\"%#\"}",
#"USRfa9210bad85165d5",
#"<Root Bookmark=\\\"Page1\\\">\\u000d\\u000a<Name>MyName</Name>\\u000d\\u000a<Address>MyAddress</Address></Root>"];
BTW, have you checked the variable '_responseData'? I think it's also empty.

Related

Passing Spanish Language Data through JSON

I am fetching location data from foursquare api and then passing this data to webservice to insert in the database.
Now e.g. when i get location data for Mexico city then there are some special characters in it which gives following error:-
Unrecognized escape sequence. (13443):
Right now i am using following encoding for JSON parsing:-
NSString *requestString = [jsonstring UTF8String];
How can i parse Special character(Spanish Data) e.g Éspanol in JSON?
Any solution?
Thanks.
I was also having the same issue earlier with json. I solved this special character issue by using the following code:-
+(NSString *)http_post_method_changed:(NSString *)url content:(NSString *)jsonContent
{
NSURL *theURL = [NSURL URLWithString:url];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0f];
NSData *requestData = [jsonContent dataUsingEncoding:NSUTF8StringEncoding];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[theRequest setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[theRequest setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody: requestData];
NSURLResponse *theResponse = NULL;
NSError *theError = NULL;
NSData *theResponseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];
NSString *data=[[NSString alloc]initWithData:theResponseData encoding:NSUTF8StringEncoding];
NSLog(#"url to send request= %#",url);
NSLog(#"response1111:-%#",data);
return data;
}
Pass your url and json to send and it will provide you the desired response.
Did you use this?
NSArray *dataArray =
[NSJSONSerialization JSONObjectWithData:_data
options:NSJSONReadingAllowFragments
error:&error];
Make sure (by consulting the forsquare api docs) that the feed is indeed in UTF-8 - then the above should work without errors.
This assumes the API feed is sending you an array, use NSDictionary otherwise.

Posting data from iphone app to server

I am sending data from iphone application to server but when it reads post String it crashes in the application and do not move forward
-(void)submitSurveyAnswers{
NSString*survey_question_response_id="1";
NSString*survey_id=#"1";
NSString *question_id =#"1";
NSString *survey_response_answer_id =#"1";
NSString *post =[[NSString alloc] initWithFormat:#"survey_question_response_id=%#&survey_id=%#&question_id=%#&survey_response_answer_id=%#",survey_question_response_id,survey_id,question_id,survey_response_answer_id];
NSLog(post);
NSURL *url=[NSURL URLWithString:#"http://myserver-solutions.com/app/surveyAnswer.php?"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"%#",data);
}
You have created one string with below way:
NSString*survey_question_response_id="1"; //Missing '#' while initializing string
It should be created like below way:
NSString*survey_question_response_id=#"1"; //Added '#' while initializing string
NSString*survey_question_response_id="1";
is wrong. Strings between plain double quotes are C string (0-terminated character pointers), and aren't valid NSString instances. I'm sure you wanted to 1. learn to use a debugger 2. write
NSString *survey_question_response_id = #"1";
instead.

converting image to base64 and uploading in JSON format to server

I have a problem. I need to convert base64 string to JSON string and pass it to server.
for example I have a base64 string /9j/4AAQSkZJRgABAQAAAQABAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAACqADAAQAAAABAAAACgAAAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/Z
i need to convert it to JSON format. I do the following:
+(NSData *)prepareForUploading:(NSString *)base64Str
{
NSDictionary *dict=[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:base64str, nil] forKeys:[NSArray arrayWithObjects:#"picture", nil]];
NSData *preparedData=[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
return preparedData;
};
here how I'm making NSURLRequest
-(NSString *)uploadPict:(NSString *)pict
{
NSLog(#"Server: upload: called");
NSData *prepPictData=[[self class] prepareForUploading:pict];
NSString *preparedBase64StrInJSON=[[NSString alloc] initWithData:prepPictData encoding:NSUTF8StringEncoding];
//here I'm adding access token to request
NSString *post = [NSString stringWithFormat:#"accessToken=%#&object=%#", self.key, preparedBase64StrInJSON];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#upload.aspx", serverAPIPath]]];
[request setHTTPMethod:#"POST"];
[request setValue:#"postLength" forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *error;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//....
}
But I get "Invalid length for a Base-64 char array" from server. What's wrong?
If I paste my token and JSON to http://hurl.it/ and make request using it - everything goes normally.
I think the problem is / symbols in base64 string and as a result / symbols in JSON.
Maybe it is something with [postData length]: if I erase \/ characters from JSON string:
9j4AAQSkZJRgABAQAAAQABAAD4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAACqADAAQAAAABAAAACgAAAAD2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQHZ request will perform normally but this base64 encoded string is not the same.
Please, help me to solve this problem
jString is your base64 string, first use following line
[self encodeString:jString];
and then call use following.
NSString *URL = [NSString stringWithFormat:#"forms.asmx/CreateUpdate?"];
URL=[NSString stringWithFormat:#"%#%#", USERS_API_ROOT_URL, URL];
NSString *post = [NSString stringWithFormat:#"apiKey=A0B1I2L3A4L5-A1D3-4F30-5AB2-C8DEE266&strPost=%#",jString];
unsigned long long postLength = [post length];
NSString *contentLength = [NSString stringWithFormat:#"%llu",postLength];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:URL]];
[request setHTTPMethod:#"POST"];
[request setValue:contentLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData ];
(void)[[NSURLConnection alloc] initWithRequest:request delegate:self];
-(NSString *)encodeString:(NSString *)string
{
NSString *newString = (__bridge_transfer NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)string, NULL,CFSTR(":/?#[]#!$ &'()*+,;=\"<>%{}|\\^~`"), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
return newString;
}
Hope it will work.

How to set the format of JSON post method in iphone

I'm sending a post request through webservices but I'm not getting the response I want.
Here's my code:
NSString *newurlString = [NSString stringWithFormat:#"{\"name\":\"asit\",\"email\":\"m.kulkarni#easternenterprise.com\",\"businessType\":\"1\",\"score\":30}"];
NSString * url = #"http://www.nieuwe-dag.nl/mobile_be/public/?action=saveScore";
//NSString *urlString =[NSString stringWithFormat:#"name=%#&email=%#&businessType=%d&score=%d",name, email, bussinesstype, score];
NSData *postData = [newurlString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSLog(#"urlString::%#",newurlString);
NSLog(#"postLength::%#",postLength);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:300];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *theConnection =[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection){
webData = [[NSMutableData data] retain];
}
else {
NSLog(#"theConnection is NULL");
}
You are setting the request type to json but you are not creating a json. The data you are creating is just nsstring. I think you need to create a json object. You can download JSON API from here:
https://github.com/stig/json-framework/
Use [SBJSONWriter dataWithObject:] to create a JSON object. Then pass it to your request.
FOr more info on JSON:
http://www.json.org/
You need proper postData
NSDictionary *dataDict = #{
#"name": #"asit",
#"email": #"m.kulkarni#easternenterprise.com",
#"businessType": #"1",
#"score": #(30)
};
NSData *postData = [NSJSONSerialization dataWithJSONObject:dataDict options:0 error:nil];

Why this POST don't work?

this is my snippet:
NSString *post = #"from=A&name=B&email=ciccio#aaasd.com&messaggio=MESSAGE&codHidden=-1";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://www.mysite.com/page.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSLog(#"Succeeded! Received %d bytes of data",[urlData length]);
NSString *outputdata = [[NSString alloc] initWithData:urlData encoding:NSASCIIStringEncoding];
NSLog(#"%#", outputdata);
It call a php page that send me an email...
Is there any errors in this code?
Does not seem to work...
thanks
Is it a Synchronous/Asynchronous problem? If so, use the delegate-pattern and access the data asynchronously. Could you post any errors you see (or the server's response string)?
EDIT: Since you're not doing anything useful with the error returned, change your class to do the request asynchronously. A great answer to this was previously posted here. Once you implement didFailWithError you'll have a better picture.
Try to change NSASCIIStringEncoding to NSUTF8StringEncoding