现在的位置: 首页 > 综合 > 正文

(转)从Internet获取网页数据

2012年05月30日 ⁄ 综合 ⁄ 共 885字 ⁄ 字号 评论关闭

 

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);  

 

【上篇】
【下篇】

抱歉!评论已关闭.