(转)从Internet获取网页数据

本文介绍了一种使用Java中的HttpURLConnection对象从指定URL抓取网页数据的方法。通过设置连接超时并读取输入流,可以成功获取网页内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

Code:
  1. 利用HttpURLConnection对象,我们可以从网络中获取网页数据.  
  2. URL url = new URL("http://www.sohu.com");  
  3. HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  4. conn.setConnectTimeout(61000);//设置连接超时  
  5. if (conn.getResponseCode() != 200throw new RuntimeException("请求url失败");  
  6. InputStream is = conn.getInputStream();//得到网络返回的输入流  
  7. String result = readData(is, "GBK");  
  8. conn.disconnect();  
  9. System.out.println(result);  
  10. //第一个参数为输入流,第二个参数为字符集编码  
  11. public static String readData(InputStream inSream, String charsetName) throws Exception{  
  12.     ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
  13.     byte[] buffer = new byte[1024];  
  14.     int len = -1;  
  15.     while( (len = inSream.read(buffer)) != -1 ){  
  16.         outStream.write(buffer, 0, len);  
  17.     }  
  18.     byte[] data = outStream.toByteArray();  
  19.     outStream.close();  
  20.     inSream.close();  
  21.     return new String(data, charsetName);  

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值