經常, 我們用通過這樣的方法調用API。
NSString* urlString = [NSString stringWithFormat:@"http://api.douban.com/v2/movie/search?q=%@", content]; NSURL *url = [NSURL URLWithString:urlString]; testRequest = [ASIHTTPRequest requestWithURL:url]; [testRequest setDelegate:self]; [testRequest startAsynchronous];
但是, 當路徑中存在中文的時候. ASI就無法正常訪問那個url。
報錯如下:
Error Domain=ASIHTTPRequestErrorDomain Code=5 "Unable to create request (bad url?)" UserInfo=0x109697090 {NSLocalizedDescription=Unable to create request (bad url?)}
解決辦法:
轉碼.
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
完整代碼:
NSString* urlString = [NSString stringWithFormat:@"http://api.douban.com/v2/movie/search?q=%@", content]; urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:urlString]; testRequest = [ASIHTTPRequest requestWithURL:url]; [testRequest setDelegate:self]; [testRequest startAsynchronous];