我們平常常這樣調用 API:
NSString *urlString = [NSString stringWithFormat:@"https://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?)}解決辦法很簡單:對 URL 做百分比轉碼。
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
完整程式碼如下:
NSString *urlString = [NSString stringWithFormat:@"https://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];
關鍵就在那一行 stringByAddingPercentEscapesUsingEncoding:它把中文等非 ASCII 字元編碼成合法的 URL 形式,NSURL 便能正確解析、請求也隨之成功。