如何在java中以正确的字符编码从给定URL获取源代码?
我有一个表示url的字符串,我需要获取它的HTML源代码。 问题是,我找不到正确编码的方法(像字母“aìòù”这样的字母没有正确阅读,只是作为“?”接收) 最好的办法是什么?我遇到了很多解决方案,但显然没有一个有效 这是我的密码如何在java中以正确的字符编码从给定URL获取源代码?,java,html,encoding,Java,Html,Encoding,我有一个表示url的字符串,我需要获取它的HTML源代码。 问题是,我找不到正确编码的方法(像字母“aìòù”这样的字母没有正确阅读,只是作为“?”接收) 最好的办法是什么?我遇到了很多解决方案,但显然没有一个有效 这是我的密码 private String getHtml(String url, String idSession) throws IOException { URL urlToCall = null; String html = ""; t
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上不起作用。
String url = "http://www.hamzaalayed.com/";
Document document = Jsoup.parse(new URL(url).openStream(), "utf-8", url);
Element paragraph = document.select("p").first();
for (Node node : paragraph.childNodes()) {
if (node instanceof TextNode) {
System.out.println(((TextNode) node).text().trim());
}
}