How to ios connect web service and get json data? - iphone

When I connect to web services that return Json strings it returns them like XML:
2014-02-07 00:17:15.673 Test[791:70b] <\?xml version="1.0" encoding="utf-8"?>
<\string xmlns="MBSCafe.Service.ServiceManager">{"query": [{"ID": "01","Name": "food"}]}<\/string>
Instead, I want this:
{"query": [{"ID": "01","Name": "food"}]}
This is my part of code:
NSString *urlString = #"http://mbsserver/MBSCafeService/ServiceManager.asmx/GetItemTypeList";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod: #"POST"];
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Accept"];
NSString *myRequestString = #"id="; // Attention HERE!!!!
myRequestString = [myRequestString stringByAppendingString:#"01"];
NSData *requestData = [NSData dataWithBytes:[myRequestString UTF8String] length:[myRequestString length]];
[request setHTTPBody: requestData];
What is wrong with it?

Make sure server return response in json format first, you can check it by fidder or other Firefox, Chrome plugins

Test your webservice using the firefox plug-in called "HTTP resource test", specify your parameters there and see what response you are getting. You can find this plug-in using firefox->tools->HTTP resource test.

Related

json post request method

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic
options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *encodedString = [jsonString base64EncodedString];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#wsName",baseUrl]];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:encodedString forHTTPHeaderField:#"Data"];
This doesn't make sense. You're creating JSON, base-64 encoding it (you never have to base-64 encode JSON; if you were really trying to encrypt it, you have to come up with something better), and setting the header Data with this, while simultaneously providing a Content-Type informing the server that the request was XML, even though it wasn't.
If the server was expecting JSON, you'd just send JSON:
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:&error];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#wsName",baseUrl]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request addValue: #"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:jsonData];
If the server was expecting XML, you'd use the text/xml or application/xml setting for Content-Type, but you'd also (a) have to construct the XML content; and (b) supply that to setHTTPBody.
If you wanted to secure the request, you'd use https://.
Bottom line, you must confirm what precisely the server is looking for. Don't guess, but rather look at the server's source code or documentation or talk to the developers. But your client-side code sample is unlikely to work as it stands.

NSMutableURLRequest loses session information

I have an iphone app that I'm trying to get to talk to a rails back end. I'm using NSMutableURLRequest to pull data back and forth. All the calls work fine on GET requests but when I need to post data, my rails app can't seem to find the session. I've posted the code below for both a get and a POST request.
This is the POST request:
//Set up the URL
NSString *url_string = [NSString stringWithFormat:#"https://testserver.example.com/players.xml"];
NSURL *url = [NSURL URLWithString:url_string];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:30];
//To create an object in rails
//We have to use a post request
////This is the format when using xml
NSString *requestString = [[NSString alloc] initWithFormat:#"<player><team_game_id>%#</team_game_id><person_id>%#</person_id></player>", game, person];
NSData *requestData = [NSData dataWithBytes:[requestString UTF8String] length:[requestString length]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:requestData];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
//For some reason rails will not take application/xml
[request setValue:#"application/xml" forHTTPHeaderField:#"content-type"];
The get request is:
NSString *url_string = [NSString stringWithFormat:#"https://testserver.example.com/people/find_by_passport?passport=%i", passport];
passportString = [[NSMutableString alloc] initWithFormat:#"%i", passport];
NSLog(#"The passport string is %#", passportString);
NSLog(url_string, nil);
NSURL *url = [NSURL URLWithString:url_string];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:30];
I am at my wits end here trying to find out whats going on so any help would be GREATLY appreciated.
Faced the same issue. Parse the response headers for the Set-Cookie header, extract the cookies by hand, pass them back as Cookie: header on subsequent requests.
If this is just about sessions in their simplest, you don't have to worry about persistence, HTTPS, domains/paths and such.
EDIT: I found class NSHTTPCookieStorage. See if it can be of help...

how send data saved in local xml file to server? objectivec

I have an project in which i retrieve data from user and save in local xml file. I have done all this on simulator. Now i want to deploy on iPhone device. But problem is that how send file (XML) from iphone to server by using web services?
You can HTTP POST it:
NSString * xmlString = #"<test><message length="5">Hello</message></test>";
NSURL * serviceUrl = [NSURL URLWithString:#"http://my.company.com/myservice"];
NSMutableURLRequest * serviceRequest = [NSMutableURLRequest requestWithURL:serviceUrl];
[serviceRequest setValue:#"text/xml" forHTTPHeaderField:#"Content-type"];
[serviceRequest setHTTPMethod:#"POST"];
[serviceRequest setHTTPBody:[xmlString dataUsingEncoding:NSASCIIStringEncoding]];
NSURLResponse * serviceResponse;
NSError * serviceError;
serviceResponse = [NSURLConnection sendSynchronousRequest:serviceRequest returningResponse:&serviceResponse error:&serviceError];
Taken from here

SOAP Xml issue in iPhone

Methods which take no parameter give correct result as expected. Whereas methods of webservice requiring few parameter returns no relevant result instead show Message.
Im using following code:
NSString *post =[[NSString alloc] initWithFormat:#"param1=%#&param2=%#&param3=%#&param4=%#&pageSize=%#&pageNo=%#",#"",#"81",#"1",#"",#"40",#"1"];
NSURL *url = [NSURL URLWithString:#"www.someurlxyz.com"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
soapMsg = [soapMsg stringByAppendingString:post];
NSLog(#"value of soap is %#",soapMsg);
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMsg length]];
//postData =[postData stringByAppendingString:];
[req addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[req addValue:#"http://www.someurlxyz.com/Search/Methodname?" forHTTPHeaderField:#"SOAPAction"];
[req addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[req setHTTPMethod:#"POST"];
[req setHTTPBody: [soapMsg dataUsingEncoding:NSUTF8StringEncoding]];
[post release];
Message (which is getting returned is following).
Server did not recognize the value of HTTP Header SOAPAction: http://www.someurlxyz.com/Search/Methodname?
Might be a problem with the namespaces or you might be calling a wrong method.
Use some third party client like SoapUI to check your webservice, and check whether you creating exact string in your request in iPhone app.
What is the server expecting here?
It looks like you are sending param1=&param2=81&param3=1&param4=&pageSize=40&pageNo=1
Which doesn't look like an actual soap message or even XML.
You don't specify what soapMsg is originally but you're appending the string above to it.
Maybe you intended to format the original soapMgs string?

iPhone HTTPS post with xml header

I have to make a HTTPS Post with some XML data, but I need to send the XML in the HTTP header.
Using the body I would do something like this
request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:CACHE_POLICY timeoutInterval:TIMEOUT_INTERVAL];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
[request setHTTPBody:postData];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
But this does not work for the header, anyone know how to make this?
The XML is something like this
<request>
<code1>666</code1 >
<code2>656</code2 >
<code3>767</code3 >
</request >
Thanks.
[request setValue:#"<request><code1>666</code1 ><code2>656</code2 ><code3>767</code3 ></request >" forHTTPHeaderField:#"Your header field name?"];
Or do you mean "in the URL", rather than a random header? HTTP Headers aren't for bunging random data into, in ordinary circumstances.
Off the top of my head, without trying to compile (no Xcode with me right now), excuse typos:
NSMutableString *urlString = [NSMutableString string];
[urlString append:#"http://wahtever.com?something=something"];
[urlString append:#"&data="];
[urlString append:[#"<request>...etc</request>" stringByAddingPercentEscapesUsingEncoding:UTF8StringEncoding];
NSURL *url = [NSURL URLwithString:urlString];
request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:CACHE_POLICY timeoutInterval:TIMEOUT_INTERVAL];