/**
* 获取URL指定的资源
*
* @param htmlFile
* @return
* @throws IOException
*/
public static String getHtmlResourceByURL(String htmlFile) throws IOException {
String result = "";
try {
URL url = new URL(htmlFile);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
String charset = "UTF-8";
Pattern pattern = Pattern.compile("charset=\\S*");
Matcher matcher = pattern.matcher(conn.getContentType());
if (matcher.find()) {
charset = matcher.group().replace("charset=", "");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(is, charset));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
HttpURLConnection获取网页内容(解决乱码)
最新推荐文章于 2019-07-04 09:56:33 发布