iOS Bad URL for NSUrlConnection - objective-c

I have a url in an NSString called myUrl. When I NSLog myUrl I see the following:
http://dl.dropbox.com/u/57665723%2FChocolatesRUs%2FJellies%2FUn-sugared%2Fgen%20no%20sugar.pdf
I then try connecting using this url as follows:
NSURL* url = [ NSURL URLWithString:nextFileURL ];
NSMutableURLRequest* request = [ [ NSMutableURLRequest alloc ] initWithURL: url ];
NSURLConnection* conn = [ [ NSURLConnection alloc ] initWithRequest: request delegate: self ];
I am getting the following error:
errorcode=-1000, error=Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0x27e540 {NSUnderlyingError=0x26d800 "bad URL", NSLocalizedDescription=bad URL}
I have tried using
NSString* myUrl = [myUrl stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
but this doesn't work either.
Can anyone see the problem?

Maybe you can escape your url with stringByAddingPercentEscapesUsingEncoding instead of stringByReplacingPercentEscapesUsingEncoding.

stringByAddingPercentEscapesUsingEncoding is remove spaces and adding percents
NSString *urlString =[NSString stringWithFormat:#"&street=%#&street2=&city=%#&state=%#&
zipcode=%#&candidates=10", address.address2,address.city, address.state, address.zip5];
NSLog(#"BAD URL - %#",urlString ); // there is space in url
NSString *encodedUrl = [urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSLog(#" CORRECT URL - %#", encodedUrl); // url encode that space by %20
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL RLWithString:encodedUrl]];

Related

Why, after setting an NSHTTPCookie, is it not appended to the NSURLRequest?

I am setting (or attempting to set) an NSHTTPCookie as follows:
+ (void)setCookie {
NSString* cookieName = #"MyCookieName";
NSString* cookieValue = #"MyCookieValue";
NSString* cookieOriginURL = #"www.mycompany.com";
NSString* cookiePath = #"/";
NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
[cookieProperties setObject:cookieName forKey:NSHTTPCookieName];
[cookieProperties setObject:cookieValue forKey:NSHTTPCookieValue];
[cookieProperties setObject:cookieOriginURL forKey:NSHTTPCookieOriginURL];
[cookieProperties setObject:cookiePath forKey:NSHTTPCookiePath];
[cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:3600] forKey:NSHTTPCookieExpires];
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
}
After this method is called, I create an NSURLRequest:
NSString *urlAddress = #"http//:www.mycompany.com/mobile/home";
//Create a URL object.
NSURL *url = [NSURL URLWithString:urlAddress];
//URL Request Object
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
NSLog(#"Here's the request: %#", [requestObj description]);
//Load the request in the UIWebView.
[self.webView loadRequest:requestObj];
But the output is:
Here's the request: <NSURLRequest: 0xa33a4d0> { URL: http:www.mycompany.com/mobile/home
I expected to see the cookie info appended to the request, but it is not.
I don't know much about cookies, so I don't know if my code is missing something, or if I'm just miss interpreting what the output means.
Thanks for any help.
I doubt that the description of the NSURLRequest will provide the cookie information.
The domains are a match (cookie and the URL), so the cookie must be appended to the request. Execute the following code before firing the request to see which cookies are sent along with your request.
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for(NSHTTPCookie *cookie in [cookieJar cookiesForURL:url]) {
NSLog(#"Cookies attached: %#", cookie.description);
}

iOS: Show PDF in WebView

I´m trying to show a pdf in a webview, but the webview is always white / blank.
if i log the path from the local file, it can be logged, so the file is there..
Here is my code:
NSString *path = [[NSBundle mainBundle] pathForResource:#"fileName" ofType:#"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
(webView is an iboutlet)
Maik
Please make sure the User Interaction Enabled & Multiple Touch are enabled.
Your targetURL is maybe nil, please debug this.
If the targetUrl is nil, this is maybe the 'path' has space.
So you should encode the path:
//Encode Url
+(NSString *) urlEncodeString:(NSString *) str
{
return [str stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
}
Controlling the whole characters rather than not just the space is more appropriate.Try this one for encoding the path of a file.
-(NSString *)urlenc:(NSString *)val{
CFStringRef safeString =
CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)val,
NULL,
CFSTR("/%&=?$#+-~#<>|*,.()[]{}^!şığüöçĞÜŞİÖÇ"),
kCFStringEncodingUTF8);
return [NSString stringWithFormat:#"%#", safeString];
}

Bad URL Error With NSURLRequest

I have a NSURLRequest created next way:
NSString *url=[NSString stringWithFormat:#"http://myserveradress.com/api/users/register?register_password=%#&register_password_confirm=%#&register_email=%#&register_terms=1&register_user=%#&process_registration=1&register_name=%#"
,
[password stringByReplacingOccurrencesOfString:#" " withString:#"%"],[confirm stringByReplacingOccurrencesOfString:#" " withString:#"%"],[email stringByReplacingOccurrencesOfString:#" " withString:#"%"],[user stringByReplacingOccurrencesOfString:#" " withString:#"%"],[realName stringByReplacingOccurrencesOfString:#" " withString:#"%"]
];
NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:url]];
NSError *error;
NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
NSString *result_string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return result_string;
The result string is http://myserveradress.ru/api/users/register?register_password=password&register_password_confirm=password&register_email=myname#mail.com&register_terms=1&register_user=myname&process_registration=1&register_name=Artem%Kulikov and the error states
Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0x71e62b0 {NSUnderlyingError=0x71e6470 "bad URL", NSLocalizedDescription=bad URL}
In browser the link works fine. The problem is only in the app.
That is not the proper way to escape the strings, there is a method for that, stringByAddingPercentEscapesUsingEncoding:. So change it to:
NSString *url = [NSString stringWithFormat:#"http://myserveradress.com/api/users/register?register_password=%#&register_password_confirm=%#&register_email=%#&register_terms=1&register_user=%#&process_registration=1&register_name=%#"
, password, confirm, email, user, realName];
NSString *properlyEscapedURL = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:properlyEscapedURL]];
Not to mention the proper escape code for a space is %20 not %.
#user1506704, you are not use encoding method like in register_name, Are there spaces or other special characters in the register_name? Use NSString method stringByAddingPercentEscapesUsingEncoding:.
You can try and escape the URL:
- (NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding`

Unable to create Request: Bad URL

When i try to look for a location like this: Florida,USA it goes OK, but when i try it like this: Florida USA, i got that error:
Unable to create Request (bad url?)
The problem belongs with the spaces on the location taped, is there any way to resolve that?
NSString *urlString = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/geocode/json?address=%#&sensor=true",theLocationString];
//Create a URL object.
NSURL *url = [NSURL URLWithString:urlString];
ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
I think the problem is that you need to urlencode your string. A space character isn't a valid url string:
NSString *urlString = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/geocode/json?address=%#&sensor=true",theLocationString];
//Create a URL object.
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:
NSASCIIStringEncoding]];
ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
If NSASCIIStringEncoding doesn't work you could try: NSUTF8StringEncoding
..fredrik

extract data from cocoa http get request

I implemented the following code:
NSURL *url = [ NSURL URLWithString:[ NSString stringWithFormat: #"http://www.google.com/search?q=%#", query ] ];
NSURLRequest *request = [ NSURLRequest requestWithURL: url ];
I want to extract the body from what I receive back from the url above. I attempted:
NSData *data = [request HTTPBody];
The data variable doesn't return any data? Am I going about extracting the data out of the request the right way?
Thanks!
If you're just trying to get a web page, you can use this.
NSURL *url = [ NSURL URLWithString: [ NSString stringWithFormat: #"http://www.google.com"] ];
NSString *test = [NSString stringWithContentsOfURL:url];
If you really want to convert the data from NSData you can use this:
NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSURLRequest just defines a request — it doesn't do anything by itself. To actually make a request, you need to give the request to an NSURLConnection.
Also, as indicated in the documentation, the HTTPBody is data that's sent with the request, not the response body.
There is an article on www.eigo.co.uk which shows exactly how to do the request and get the response in a string variable but the chunk of code you need is...
NSString * strResult = [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
Check out the article here http://www.eigo.co.uk/iPhone-Submitting-HTTP-Requests.aspx