取网页的两种方式.可直接使用

java

1: CloseableHttpClient 

[java] view plain copy
  1. /* 
  2.      * 爬取网页信息 
  3.      */  
  4.     private static String pickData(String url) {  
  5.         CloseableHttpClient httpclient = HttpClients.createDefault();  
  6.         try {  
  7.             HttpGet httpget = new HttpGet(url);  
  8.             CloseableHttpResponse response = httpclient.execute(httpget);  
  9.             try {  
  10.                 // 获取响应实体  
  11.                 HttpEntity entity = response.getEntity();  
  12.                 // 打印响应状态  
  13.                 if (entity != null) {  
  14.                     return EntityUtils.toString(entity);  
  15.                 }  
  16.             } finally {  
  17.                 response.close();  
  18.             }  
  19.         } catch (ClientProtocolException e) {  
  20.             e.printStackTrace();  
  21.         } catch (ParseException e) {  
  22.             e.printStackTrace();  
  23.         } catch (IOException e) {  
  24.             e.printStackTrace();  
  25.         } finally {  
  26.             // 关闭连接,释放资源  
  27.             try {  
  28.                 httpclient.close();  
  29.             } catch (IOException e) {  
  30.                 e.printStackTrace();  
  31.             }  
  32.         }  
  33.         return null;  
  34.     }  


2:模拟浏览器:

[java] view plain copy
  1. /* 
  2.  * 爬取网页信息 
  3.  */  
  4. public static String sendGet(String url) throws Exception {  
  5.     String result = "";  
  6.     URLConnection conn = null;  
  7.     InputStream inputStream = null;  
  8.     BufferedReader in = null;  
  9.   
  10.     URL realURL = new URL(url);  
  11.     conn = realURL.openConnection();  
  12.     conn.setRequestProperty("accept""*/*");  
  13.     conn.setRequestProperty("connection""Keep-Alive");  
  14.     conn.setRequestProperty("user-agent",  
  15.             "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36");  
  16.     Map<String, List<String>> map = conn.getHeaderFields();  
  17.     for (String s : map.keySet()) {  
  18.         System.out.println(s + "-->" + map.get(s));  
  19.     }  
  20.     inputStream = conn.getInputStream();  
  21.     String line;  
  22.     // 读取操作  
  23.     in = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));  
  24.     while ((line = in.readLine()) != null) {  
  25.         result += "\n" + line;  
  26.     }  
  27.   
  28.     in.close();  
  29.   
  30.     System.out.println(result);  
  31.     return result;  
  32. }  
  • 发表于 2017-11-13 17:17
  • 阅读 ( 1215 )
  • 分类:Java

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
不写代码的码农
- Nightmare

33 篇文章

作家榜 »

  1. 威猛的小站长 124 文章
  2. Jonny 65 文章
  3. 江南烟雨 36 文章
  4. - Nightmare 33 文章
  5. doublechina 31 文章
  6. HJ社区-肖峰 29 文章
  7. 伪摄影 22 文章
  8. Alan 14 文章