一。android获取网页信息要放到线程中,否则,InputStream instr = ucon.getInputStream()会报错
try {
new Thread(new Runnable() {
@Override
public void run() {
String htmlStr = HtmlUtil.getHtmlString(myurl);
Document document = Jsoup.parse(htmlStr);
String title = document.head().getElementsByTag("title").text();
dbutil.insert(title, htmlStr, myurl, FileUtil.getCurrentTime(0), "html");
}
}).start();
Toast.makeText(this, "收藏成功", 0).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "收藏失败", 0).show();
}
public static String getHtmlString(String urlString) {
try {
URL url = new URL(urlString);
URLConnection ucon = url.openConnection();
InputStream instr = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(instr);
ByteArrayBuffer baf = new ByteArrayBuffer(500);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
return EncodingUtils.getString(baf.toByteArray(), "utf-8");
} catch (Exception e) {
return "";
}
}
二。第二种获取网页信息的方式
public static String getHtml(String address) {
try {
URL url = new URL(address);
HttpURLConnection conn;
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5000);
int code = conn.getResponseCode();
if (code == 200) {
InputStream is = conn.getInputStream();
byte[] b = getBytes(is);
return new String(b);
} else {
throw new IllegalStateException("无法访问网路");
}
} catch (IOException e) {
throw new IllegalStateException("无法访问网路");
}
}
public static byte[] getBytes(InputStream is) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int len = 0;
while ((len = is.read(b)) != -1) {
bos.write(b, 0, len);
}
is.close();
bos.flush();
return bos.toByteArray();
}