[英]Android HttpURLConnection and URL with special characters
請考慮以下代碼(從HTTP請求中檢索響應並打印它)。 注意:此代碼適用於標准Java應用程序。 在Android應用程序中使用代碼時,我只會遇到下面列出的問題。
public class RetrieveHTMLTest {
public static void main(String [] args) {
getListing(args[0);
}
public static void getListing(String stringURL) {
HttpURLConnection conn = null;
String html = "";
String line = null;
BufferedReader reader = null;
URL url = null;
try {
url = new URL(stringURL);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(6000);
conn.setReadTimeout(6000);
conn.setRequestMethod("GET");
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
conn.connect();
while ((line = reader.readLine()) != null) {
html = html + line;
}
System.out.println(html);
reader.close();
conn.disconnect();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
}
}
}
如果我提供URL: http:// somehost / somepath /
以下代碼工作正常。 但是,如果我將URL更改為: http:// somehost / somepath [注釋] /由於“[”和“]”字符,代碼會拋出超時異常。
如果我將URL更改為: http:// somehost / somepath%20%5Ba%20comment%5D /代碼工作正常。 同樣,因為“[”和“]”字符不存在。
我的問題是,我如何獲取URL:
http:// somehost / somepath [評論] /
進入以下格式:
HTTP://,某/ somepath%20%5Ba上%20comment%5D /
另外,我應該繼續在Android中使用HttpURLConnection,因為它無法接受帶有特殊字符的網址嗎? 如果標准在使用HttpURLConnection之前總是轉換URL?
使用URLEncoder
類:
URLEncoder.encode(value, "utf-8");
你可以在這里找到更多細節。
編輯:您應該僅使用此方法對參數值進行編碼。 不要編碼整個URL。 例如,如果您有一個URL: http : //www.somesite.com ?param1 = value1&param2 = value2那么您應該只編碼value1和value2,然后使用這些值的編碼版本形成URL。
url = URLEncoder.encode(value, "utf-8");
url = url.replaceAll("\\+", "%20");
“+”可能無法恢復
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.