Java 通过URL获取网站Html源代码

  1. 转载:http://blog.csdn.net/yanjiaye520/article/details/8990233

  2. package com.wsw.j2se.url;  
  3.   
  4. import java.io.ByteArrayOutputStream;  
  5. import java.io.InputStream;  
  6. import java.net.HttpURLConnection;  
  7. import java.net.URL;  
  8.   
  9. /** 
  10.  * 通过网站域名URL获取该网站的源码 
  11.  * @author Administrator 
  12.  * 
  13.  */  
  14. public class HtmlRequest {  
  15.     /** *//** 
  16.     * @param args 
  17.     * @throws MalformedURLException  
  18.     */  
  19.     public static void main(String[] args) throws Exception    {  
  20.         URL url = new URL("http://www.ifeng.com");   
  21.         String urlsource = getURLSource(url);  
  22.         System.out.println(urlsource);  
  23.     }  
  24.       
  25.     /** *//** 
  26.      * 通过网站域名URL获取该网站的源码 
  27.      * @param url 
  28.      * @return String 
  29.      * @throws Exception 
  30.      */  
  31.     public static String getURLSource(URL url) throws Exception    {  
  32.         HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  33.         conn.setRequestMethod("GET");  
  34.         conn.setConnectTimeout(5 * 1000);  
  35.         InputStream inStream =  conn.getInputStream();  //通过输入流获取html二进制数据  
  36.         byte[] data = readInputStream(inStream);        //把二进制数据转化为byte字节数据  
  37.         String htmlSource = new String(data);  
  38.         return htmlSource;  
  39.     }  
  40.       
  41.     /** *//** 
  42.      * 把二进制流转化为byte字节数组 
  43.      * @param instream 
  44.      * @return byte[] 
  45.      * @throws Exception 
  46.      */  
  47.     public static byte[] readInputStream(InputStream instream) throws Exception {  
  48.         ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
  49.         byte[]  buffer = new byte[1204];  
  50.         int len = 0;  
  51.         while ((len = instream.read(buffer)) != -1){  
  52.             outStream.write(buffer,0,len);  
  53.         }  
  54.         instream.close();  
  55.         return outStream.toByteArray();           
  56.     }  
  57. }  
  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值