Get content of webservice - iphone

I've got an URL like here. When I type that into Safari's address bar I see an result like "Error" or "OK".
So, how do I properly call that URL from within my code and get that result as a string?
I've tried it with NSURLConnection, NSURLRequest and NSURLResponse but my response object is always nil.

The "response" in those classes refers to the protocol response (HTTP headers, etc.), not the content.
To get the content, you have a few options:
Use NSURLConnection in asynchronous mode: Using NSURLConnection
Use NSURLConnection in synchronous mode:
// Error checks omitted
NSURL *URL = [NSURL URLwithString:#"http://www.myserver.com/myservice.php?param=foobar"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil
error:nil];
Use [NSString stringWithContentsOfURL:]
NSURL *URL = [NSURL URLwithString:#"http://www.myserver.com/myservice.php?param=foobar"];
NSString *content = [NSString stringWithContentsOfURL:URL];
Of course, you should use options 2 and 3 only if your content will be really small in size, to maintain responsiveness.

Related

Can't fetch data from NSURL

I am fetching result from google place search url, if I search for "Newyork", everything works fine. But if I give "New york", the result json is different and I can't take it in NSData.
This is the url I am using:
https://maps.googleapis.com/maps/api/place/textsearch/json?query=New york&sensor=true&key=MY_KEY
I am using below code to fetch the data:
NSURL *googleURL = [NSURL URLWithString:url]; //url is above url
NSURLResponse *response;
NSData *data;
NSError *error;
data = [NSURLConnection sendSynchronousRequest: [NSURLRequest
requestWithURL: googleURL] returningResponse: &response error: &error];
NSLog(#"data %#",data); // but I am getting null here
How to overcome this? Thanks in advance
Assuming that url is:
NSString *url = #"https://maps.googleapis.com/maps/api/place/textsearch/json?query=New york&sensor=true&key=MY_KEY";
Try using this:
NSURL *googleURL = [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
This will format the string for URLs containing spaces. To confirm it is working, print it out to the console.
NSLog(#"URL with Percent Escapes: %#", [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]);
It should return something like this (I believe the percent escape for a space is %20).
URL with Percent Escapes: https://maps.googleapis.com/maps/api/place/textsearch/json?query=New%20york&sensor=true&key=MY_KEY

getting error during json parsing

I am getting error during json parsing. When I trying to send the parameters using browser then it send me the success message that record store successfully. But when I send form parameters through iphone then i get nothing and in array i get NULL value.This is the json parsing code.
NSString *string1 = [[NSString alloc]initWithFormat:#"http://195.78.76.34/bedspace/mobileapi.php?action=save_room_info&Area=%#&Address=%#&Living_room=%#&Amenties=%#&Type_of_cost=%#&cost_of_room=%#&Security_deposit=%#&STLC=%#&Days_available=%#&Bill_included=%#&Broadband_available=%#&Exc_Smoke=%#&Exc_gender=%#&Exc_pets=%#&Exc_age=%#&Exc_language=%#&Exc_nationality=%#&Exc_Sexorientition=%#&Exc_intrest=%#&Pre_smoke=%#&Pre_gender=%#&Pre_occupation=%#&Pre_pets=%#&Pre_min_age=%#&Pre_max_age=%#&Pre_nationaltiy=%#&Pre_Language=%#&Pre_Sexorientition=%#&Misc=%#&Title=%#&Description=%#&Your_name=%#&Your_email=%#&Email_alert=%#&No_of_rooms=%#&Country=%#&City=%#&State=%#&Size_of_property=%#&Type_of_property=%#&Occupets_property=%#&My_property_status=%#&Amenties_two=%#&Size_of_room=%#&Refrence_required=%#",area,address,livingRoomVal,amenties,typeOfCost,costOfRoom,securityDeposit,STLC,daysAvailable,billsIncluded,broadbandAvailable,eSmoke,eGender,ePets,eAge,eLanguage,eNationality,eSexOrientation,eInterest,pSmoke,pGender,pOccupation,pPets,pMinAge,pMaxAge,pNationality,pLanguage,pSexOrientation,misc,title,description,yourName,yourEmail,emailAlerts,noOfRooms,country,city,state,sizeOfProperty,typeOfProperty,occupentsOfProperty,myPropertyStatus,amentiesTwo,sizeOfRoom,refrenceRequired];
NSLog(#"string 1 value %#",string1);
NSURL *urlRequest = [NSURL URLWithString:string1];
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:urlRequest];
NSData *dataResponce = [NSURLConnection sendSynchronousRequest:request returningResponse:Nil error:Nil];
NSError *jsonParsingError = nil;
NSArray *publicTimeline = [NSJSONSerialization JSONObjectWithData:dataResponce options:0 error:&jsonParsingError];
NSLog(#"get values %#",publicTimeline);
I don't know what the problem is. I also used SBJsonParser but i get nothing in array and after that I used NSJSONSerialization and same problem still happen i got nothing in NSData and in NSArray.
You cannot fill the URL with parameters and still expect it to be legal, so you need to URL Encode the URL before use:
NSURL *urlRequest = [NSURL URLWithString:[string1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

How to consume post type restful wcf service in iphone?

I am consuming restful WCF service in the form of JSON of type 'GET'.
I want to know how to consume service of type 'POST' so, that i can send large amount of data.
Here is my code for Type 'GET':
NSURL *jsonURL = [NSURL URLWithString:[NSString stringWithFormat:#"http://www.xxx.com /coffeeiphone/Service.svc/maintransactioninsert/%#/%#/%#",stockid,[format stringFromDate:selected],[quantity text], nil]];
NSString *jsonData = [[NSString alloc] initWithContentsOfURL:jsonURL];
For GET, it works to just get the contents of the URL like you did above.
For POST, you will have to create an NSMutableURLRequest.
NSURL *theUrl = [NSURL URLWithString:#"yourURL"];
NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc] initWithURL:theUrl];
[theRequest setHTTPMethod:#"POST"];
//set the body of your request:
[theRequest setHTTPBody: //request here];
//get your response:
NSData *response = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:nil];
To construct JSON, try looking at the json-framework. https://github.com/stig/json-framework/

Losing a / when converting from NSURL to NSURLRequest

I'm doing an HTTP Post in my iphone app and one of the parameters I send to the server is a URL. The problem is that when I convert from an NSURL to an NSURLRequest, the string http://www.slashdot.org becomes http:/www.slashdot.org (one of the forward slashes is missing)
is there a way around this?
here is the code I'm using:
NSString *host = #"example.host.com";
NSString *urlString = [NSString stringWithFormat:#"/SetLeaderUrl.json?leader_email=%#&url=%#",localEmail,urlToPublish];
NSURL *url = [[NSURL alloc] initWithScheme:#"http" host:host path:urlString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *jsonString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
I've used NSLog to see where it loses the '/' and it's on the fourth line:
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
thanks for taking the time to read!
You're not percent-escaping the query values before substituting them in to the string. I just did a little test, and found that if I set urlToPublish to "http://example.com", then NSURL would transform it into "http:/example.com".
This is because the query value contains special characters, which means you need to add percent escapes. At the very least you can use the mediocre -[NSString stringByAddingPercentEscapesUsingEncoding:] with the NSASCIIStringEncoding. Far better would be to use a different (and more complete) escaping mechanism, such as the one I suggest in this post.
In this case, stringByAddingPercentEscapesUsingEncoding: does not work, because it's a pretty lousy method. It works on an inclusive model, which means you have to tell it which characters you want percent encoded. (Under the hood, it's just calling CFURLCreateStringByAddingPercentEscapes()) This function basically asks you for a string that represents every character it's allowed to percent-encode (as I understand the function). What you really want is an exclusive model: escape everything except [this small set of characters]. The function I linked to above does that, and you'd use it like this:
NSString *urlToPublish = [#"http://stackoverflow.com" URLEscapedString_ch];
NSString *host = #"example.host.com";
NSString *urlString = [NSString stringWithFormat:#"/SetLeaderUrl.json?leader_email=%#&url=%#",localEmail,urlToPublish];
NSURL *url = [[NSURL alloc] initWithScheme:#"http" host:host path:urlString];
And then it will build your URL properly.
Here's another way you could do this (and do it correctly). Go to my github page and download "DDURLBuilder.h" and "DDURLBuilder.m", and then build your URL like this:
NSString *localEmail = #"foo#example.com";
NSString *urlToPublish = #"http://stackoverflow.com"
DDURLBuilder *b = [DDURLBuilder URLBuilderWithURL:nil];
[b setScheme:#"http"];
[b setHost:#"example.host.com"];
[b setPath:#"SetLeaderUrl.json"];
[b addQueryValue:localEmail forKey:#"leader_email"];
[b addQueryValue:urlToPublish forKey:#"url"];
NSURL *url = [b URL];
Here is some code apple use to get a NSURLRequest,
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.apple.com/"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
#Dave DeLong: I notice in the Apple "URL Loading System Program Guide" the example creating a connection and request does not use any escaping. The Url it uses is from a NSURL URLWithString:
I fixed it, this is what I had to do:
NSString *urlString = [NSString stringWithFormat:#"/SetLeaderUrl.json?leader_email=%#&url=%#",localEmail,urlToPublish];
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
urlString = [NSString stringWithFormat:#"%#%#%#",scheme,host,urlString];
NSURL *url = [[NSURL alloc] initWithString:urlString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

Send http request with Chinese words

NSString *urlAddress = #"http://www.test.com/test.jsp?Query=哈囉";
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
NSURLResponse* myURLResponse;
NSError* myError;
NSData* data = [NSURLConnection sendSynchronousRequest: requestObj returningResponse:&myURLResponse error:& myErr];
I want to use http get method to send request, but failed.
English alphabets work well.
I.e., I want to convert "哈囉" to "%E5%93%88%E5%9B%89" so that the response will successfully return. It seems not to be converted by itself automatically.
Anyone could help me solve this problem?
Thanks a lot!
urlAddress = [urlAddress stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
(docs)