Wil*_*ann 5 java url android httpurlconnection
请考虑以下代码(从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 {
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果我提供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?
Arn*_*rty 13
使用URLEncoder课程:
URLEncoder.encode(value, "utf-8");
Run Code Online (Sandbox Code Playgroud)
你可以在这里找到更多细节.
编辑:您应该仅使用此方法对参数值进行编码.不要编码整个URL.例如,如果您有一个URL:http://www.somesite.com ?param1 = value1¶m2 = value2,那么您应该只编码value1和value2,然后使用这些值的编码版本形成URL.
| 归档时间: |
|
| 查看次数: |
9356 次 |
| 最近记录: |