views:

219

answers:

2

I'd like to submit to the following URL in a Cocoa app and save the results to a string (although XML is probably better):

http://translate.google.com/translate_t#en|fr|hi%20there%20all

The page keeps returning an error. Here's my code:

NSString *urlString = @"http://translate.google.com/translate_t#en|fr|hi%20there%20all";
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:10];
NSData *urlData;
NSURLResponse *response;
NSError *error;
urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];

NSString *content = [[NSString alloc]  initWithBytes:[urlData bytes]

The above causes the URL to turn into:

http://translate.google.com/translate_t%23en%7Cfr%7Chi%2520there%2520all

Which results in a 404 from Google. If I try the URL without escaping, I get zero bytes returned. Any ideas on how to make this work?

--- EDIT ---

The source of the problem is that the value of url is nil. Remove the EscapesUsingEncoding line (line 2) and check the value of url. I've the pipes in the URL are causing [NSURL URLWithString:urlString]; to return nil. Escaping the pipes with their hex values, 7C (http://translate.google.com/translate%5Ft#en%7cfr%7chi%20there%20all), returns data. But then I get zero bytes again on the NSString *content line.

+6  A: 

The problem is that you're escaping the # character, which is needed by Google Translate to figure out what's going on. In fact, given that the URL you are passing includes the %20 (space) then you don't actually need the URL escape code at all - you can just use your literal as is.

If you're constructing it from an NSTextField or similar, just run the URL escaping on the textValue before adding your prefix on it.

AlBlue
If I try "http://translate.google.com/translate_t#en|fr|hi there all", that does not work because the pound is escaped. If I try "http://translate.google.com/translate_t#en|fr|hi%20there%20all", I get zero bytes return. So, the literal cannot be used.
4thSpace
I've revised original post. url variable is nil, hence zero bytes, but not sure why.
4thSpace
A: 

You seem to be double-escaping the percent signs (see that if you'll take the final string into Safari it wouldn't load either, giivng a 404).

This causes the %20 to become %2520 (the %25 is the % sign). Also, not escaping at all doesn't escape the # and | signs.

Your origin string should be:

http://translate.google.com/translate_t#en|fr|hi there all
Aviad Ben Dov