檢查並且測試一下對方所給的網址, 發現原來是網址的問題
一般正常的網址大概如下, 用正常 HttpURLConnection 一切都沒問題.
http://www.yahoo.com
但是如果是以下的網址呢 ?
http://www.yahoo.com/abcabc재/test/123.html用一般正常的瀏覽器看是沒有問題, 但如果使用 HttpURLConnection 就會出現找不到網址的現象.
原因很簡單, 就是要把網址 encode.
原本很簡單的我就直接使用 URLEncode("http://www.yahoo.com/abcabc재/test/123.html", "UTF-8"),
這樣不行, 這樣會連 ":", "/" 等都給 encode 起來, 所以只能一個一個去 encode.
解決方式如下:
public static String getEncodeURL(String url) {
StringBuilder sb = new StringBuilder();
Uri uri = Uri.parse(url);
String path = uri.getPath();
List paths = uri.getPathSegments();
int index = url.indexOf(path);
sb.append(url.substring(0, index));
for (String s: paths) {
try {
sb.append("/"+URLEncoder.encode(s, "UTF-8"));
} catch (UnsupportedEncodingException e) {
sb.append("/"+s);
}
}
return sb.toString();
}
只要把每個網址用這個 method 包起來就可以了
PS: 上面那個 </string> 請忽略, 不知道為啥會出現
沒有留言:
張貼留言