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];
Related
I am using Google place API in my application. Well, its working fine and giving response for some places. But for some places, its giving "ZERO RESULTS".
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://maps.googleapis./maps/api/place/search/json?location=%f,%f&radius=5000&types=&name=%#&sensor=false&key=fgewffefewweweewfe",mapView.centerCoordinate.latitude,mapView.centerCoordinate.longitude,searchPlace.text]];
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
NSURLConnection *connect= [[NSURLConnection alloc]initWithRequest:request delegate:self];
Can anyone give me an idea where I am getting wrong?
If the location name is not valid it will give you zero results & in some cases because of extra spaces in the string you will get URL as null. So update your code as I mentioned below and check it out.
NSString *googleApi = [NSString stringWithFormat:#"https://maps.googleapis./maps/api/place/search/json?location=%f,%f&radius=5000&types=&name=%#&sensor=false&key=fgewffefewweweewfe",mapView.centerCoordinate.latitude,mapView.centerCoordinate.longitude,searchPlace.text];
NSString *finalURL = [googleApi stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:finalURL];
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
NSURLConnection *connect= [[NSURLConnection alloc]initWithRequest:request delegate:self];
It may work for you.
I am passing url with some string value and NSInteger value in this url but when I put breakpoint on this and I tab on trace then it show me this message exc-bad-access in url I given bold please see that 'bold' I want to pass there value:
[ NSInteger day,NSInteger day1,NSString *fromDate1, NSString *fromDate1,NSString *OriginCode,NSString *DestinCode].
I get all value on url when I put the breakpoint but when I step into breakpoint my app crashes, why it crash? Help me. Where am I wrong?
-(void)sendRequest
{
stringWithFormat:#"http://www.google.com?AvailabilitySearchInputFRSearchView%24ButtonSubmit=Search%20For%20Flights%20&AvailabilitySeast=",day,day1,DestinCode,"2011-09","2011-09",OriginCode];
NSString *urlString = [NSString stringWithFormat:#"http://www.bookairways tickt.com/Sales/FRSearch.aspx?AvailabilitySearchInputFRSearchView%24ButtonSubmit=Search%20For%20Flights%20&AvailabilitySearchInputFRSearchView%24DropDownListMarketDay1=**%i**&AvailabilitySearchInputFRSearchView%24DropDownListMarketDay2=**%i**&AvailabilitySearchInputFRSearchView%24DropDownListMarketDestination1=**%#**&AvailabilitySearchInputFRSearchView%24DropDownListMarketMonth1=**%#**&AvailabilitySearchInputFRSearchView%24DropDownListMarketMonth2=**%#**&AvailabilitySearchInputFRSearchView%24DropDownListMarketOrigin1=**%#**&AvailabilitySearchInputFRSearchView%24DropDownListPassengerType_ADT=1&AvailabilitySearchInputFRSearchView%24DropDownListPassengerType_CHD=0&AvailabilitySearchInputFRSearchView%24DropDownListPassengerType_INFANT=0&AvailabilitySearchInputFRSearchView%24RadioButtonFlowSelector=FlightAndCar&AvailabilitySearchInputFRSearchView%24RadioButtonMarketStructure=RoundTrip&AvailabilitySearchInputFRSearchView%24discountPax=0&__EVENTARGUMENT=&__EVENTTARGET=&__VIEWSTATE=%2FwEPDwUBMGRkg4UKvNNb1NbM14%2F2n9zUxhNQ%2B%2BA%3D&errorlist=",day,day1,DestinCode,fromDate1,fromDate2,OriginCode];
//urlString=[urlString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURL *url = [NSURL URLWithString:urlString];
NSLog(#"************url:%#",url);
NSURLRequest *theRequest=[NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
webData = [[NSMutableData data] retain];
NSLog(#"%#",webData);
} else {
}
}
make your url properly like this:-
NSURL *url = [NSURL URLWithString:[*yourstring* stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
Harish this will help u to in creating the url check this our http://wiki.akosma.com/IPhone_URL_Schemes
like this
NSString *template = #"appigotodo://com.example.xyzapp/import?name=%#¬e=%#&due-date=%#&priority=%#&repeat=%#";
NSString *name = #"Buy%20some%20milk";
NSString *note = #"Stop%20on%20the%20way%20home%20from%20work.";
NSString *dueDate = #"2009-07-16";
NSString *priority = #"1";
NSString *repeat = #"101";
NSString *stringURL = [NSString stringWithFormat:template, name, note, dueDate, priority, repeat];
NSURL *url = [NSURL URLWithString:stringURL];
[[UIApplication sharedApplication] openURL:url];
Two things:
The URL has many % symbols that are not being used as placeholders. The % symbols that are not between '**' in your code need to be escaped like so: %%. In other words, SearchInputFRSearchView%24Button should be SearchInputFRSearchView%%24Button.
You are using %i to put integers into your string. You should be using %d instead.
My iphone app called Google Local Search(non javascript version) to behave some search business.
Below is my code to form a url:
NSString *url = [NSString stringWithFormat:#"http://ajax.googleapis.com/ajax/services/search/local?v=1.0&q=%#", keyword];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"GET"];
//get response
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[[NSError alloc] init] autorelease];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
When the keyword refers to english characters, it works fine, but when refers to chinese characters(encoded in UTF8, such as '天安门' whose UTF8 code is 'e5a4a9 e5ae89 e997a8'), it will report NSURLErrorBadURL error(-1000, Returned when a URL is sufficiently malformed that a URL request cannot be initiated). Why?
Then I carry out further investigation, I use Safari and type in the url below:
http://ajax.googleapis.com/ajax/services/search/local?v=1.0&q=天安门
It also works, and the output I got from Macsniffer is:
/ajax/services/search/local?v=1.0&q=%E5%A4%A9%E5%AE%89%E9%97%A8
So I write a testing url directly in my app
NSString *url = [NSString stringWithFormat:#"http://ajax.googleapis.com/ajax/services/search/local?v=1.0&q=%E5%A4%A9%E5%AE%89%E9%97%A8"];
And what I got from the Macsniffer is some other thing:
/ajax/services/search/local?v=1.0&q=1.687891E-28750X1.417C0001416CP-102640X1.4CC2D04648FBP-9999-1.989891E+0050X1.20DC00184CC67P-953E8E99A8
It seems my keyword "%E5%A4%A9%E5%AE%89%E9%97%A8" was translated into something else. So how can I form a valid url? I do need help!
Have you tried encoding the search string:
NSString* escapedKeyword = [keyword stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
when I call
-(IBAction)goback:(id)sender
{
NSURL *xmlURL=[NSURL URLWithString:#"http://demo.komexa.com/sicherungsbereich.xml"];
NSURLRequest *request = [NSURLRequest requestWithURL:xmlURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:2];
NSURLResponse *theResponse;
NSError *theError;
NSData *myRequestResult = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&theError];
NSString *stringReply = (NSString *)[[NSString alloc] initWithData:myRequestResult encoding:NSUTF8StringEncoding];
NSLog(#"reply from server: %#", stringReply);
}
with the Iphone , on the simulator it loads the String everytime really from the internet.But on the devices, it caches the String, so even if the content of http://demo.komexa.com/sicherungsbereich.xml changes (you can do that by calling http://demo.komexa.com) the String does not automatically reload new data.
Have you got an Idea?
I have uploaded the Code here,because of formatting problems:
http://demo.komexa.com/problem.txt
just generate a random number and pass with your url , you get required result
e.g:
int randomNumber1 = 1 + arc4random()% 9;
NSString *rstr = [NSString stringWithFormat: #"%d",randomNumber1];
NSString *address = #"http://www.socialfactory.net/client-app/photovote/get_data.php";
NSString * nstr=[NSString stringWithFormat:#"%#?t=%#",address,rstr];
//NSURLRequest *theRequest=nil;
NSURLRequest * theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:nstr]];
NSURLResponse *resp = nil;
NSError *err = nil;
Maybe your Simulator and iPhone have different proxie settings. check this or try with the NSURLRequestReloadIgnoringLocalAndRemoteCacheData policy which also ignores intermediate cachings. See the docs here.
I have made a project and when people put a keyword into UITextfield and click the button then my app will retrieve the data from website database.
It is not working here is the code:
- (IBAction) btnClickMe_Clicked:(id)sender {
NSString *kw = s.text; // <-----THIS IS THE UITextField
NSURL *url = [NSURL URLWithString:#"http://www.example.com/index.php?keyword=",kw];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[iMessageLabel loadRequest:request];
}
Any one could help me?
You aren't putting the keyword into the string. You need something like this:
NSString *kw = s.text;
NSString *encodedkw = [ky stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *urlString = [NSString stringWithFormat: #"http://www.example.com/index.php?keyword=%#", encodedkw];
NSURL *url = [NSURL URLWithString:urlString];
Then look at how to use NSURLConnection to figure out how to put the data into the label.