android获取网页信息及常出的问题

一。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();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值