【发布时间】:2014-07-02 23:05:47
【问题描述】:
我有一个代表 url 的字符串,我需要获取它的 HTML 源代码。 问题是,我找不到正确编码的方法(诸如 à è ì ò ù 之类的字母没有被正确读取,只是作为“??”接收)。
最好的方法是什么?我遇到了很多解决方案,但显然没有一个有效。
这是我的代码
private String getHtml(String url, String idSession) throws IOException
{
URL urlToCall = null;
String html = "";
try
{
urlToCall = new URL(url);
}
catch (Exception e)
{
e.printStackTrace();
return "";
}
HttpURLConnection conn;
conn = (HttpURLConnection) urlToCall.openConnection();
conn.setRequestProperty("cookie", "JSESSIONID=" + idSession);
conn.setDoOutput(false);
conn.setReadTimeout(200*1000);
conn.setConnectTimeout(200*1000);
ByteArrayOutputStream output = new ByteArrayOutputStream();
InputStream openStream = conn.getInputStream();
byte[] buffer = new byte[ 1024 ];
int size = 0;
while( (size = openStream.read( buffer ) ) != -1 ) {
output.write( buffer, 0, size );
}
html = output.toString("utf-8");
return html;
}
【问题讨论】:
-
我补充说显然它不适用于 linux。