开发者

NSURLErrorBadURL error

开发者 https://www.devze.com 2022-12-24 07:35 出处:网络
My iphone app called Google Local Search(non javascript version) to behave some search business. Below is my code to form a url:

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];
开发者_如何学Python

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];

0

精彩评论

暂无评论...
验证码 换一张
取 消