HttpClient
- 网络数据都需要使用 HTTP 协议访问互联网获取,而 Java 的 HTTP 协议客户端 HpptClient 技术(就相当于一个浏览器)能更好的协助请求网络数据。
 
- 这里主要介绍 get 与 post 的带参请求,如无需参数去除参数构建与添加环节代码即可。
 
依赖:
1 2 3 4 5
   | <dependency>     <groupId>org.apache.httpcomponents</groupId>     <artifactId>httpclient</artifactId>     <version>4.5.13</version> </dependency>
   | 
 
Get 请求:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
   |  String url = "https://www.baidu.com/";
  CloseableHttpClient client = HttpClients.createDefault();
  URIBuilder uriBuilder = new URIBuilder(url)         .addParameter("a","1")         .addParameter("b","2");
  HttpGet httpGet = new HttpGet(uriBuilder.build()); CloseableHttpResponse response = null; try {          response = client.execute(httpGet);          if (response.getStatusLine().getStatusCode() == 200) {                  HttpEntity entity = response.getEntity();                  String content = EntityUtils.toString(entity, "utf8");                  System.out.println(content);     } } catch (Exception e) {     e.printStackTrace(); } finally {     if (response != null) {         try {             response.close();          } catch (IOException e) { e.printStackTrace(); }     }     try {         client.close();      } catch (IOException e) { e.printStackTrace(); } }
 
  | 
 
Post 请求:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
   |  String url = "https://www.baidu.com/";
  CloseableHttpClient client = HttpClients.createDefault();
  HttpPost httpPost = new HttpPost(url);
  List<NameValuePair> params = new ArrayList<>();
  params.add(new BasicNameValuePair("a","1"));
  UrlEncodedFormEntity em = new UrlEncodedFormEntity(params,"utf8");
  httpPost.setEntity(em);  CloseableHttpResponse response = null; try {          response = client.execute(httpPost);          if (response.getStatusLine().getStatusCode() == 200) {                  String content = EntityUtils.toString(response.getEntity(), "utf8");                  System.out.println(content);     } } catch (Exception e) {     e.printStackTrace(); } finally {     if (response != null) {         try {             response.close();          } catch (IOException e) { e.printStackTrace(); }     }     try {         client.close();      } catch (IOException e) { e.printStackTrace(); } }
 
  | 
 
连接池:
每次请求都需要创建 HTTPClient,而频繁的创建与销毁会造成资源的浪费,此时我们就可以通过使用连接池来管理 HTTPClient。(与数据库连接池原理相同)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
   |  PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
  cm.setMaxTotal(100);
  cm.setDefaultMaxPerRoute(10);
  CloseableHttpClient httpclient = HttpClients.custom()         .setConnectionManager(cm).build(); 
  HttpGet httpGet = new HttpGet("https://www.baidu.com/"); CloseableHttpResponse response = null; try {     response = httpclient.execute(httpGet);     if (response.getStatusLine().getStatusCode() == 200) {         String content = EntityUtils.toString(response.getEntity(), "utf8");         System.out.println(content);     } } catch (IOException e) {     e.printStackTrace(); } finally {     if (response != null) {         try {             response.close();         } catch (IOException e) {e.printStackTrace(); }     }
            }
 
  | 
 
注意:由连接池管理的客户端对象是不用我们来关闭的,由连接池直接管理。
配置请求:
1 2 3 4 5 6 7 8 9 10
   |  HttpGet httpGet = new HttpGet();
  RequestConfig config = RequestConfig.custom()         .setConnectTimeout(1000)          .setConnectionRequestTimeout(500)          .setSocketTimeout(10*1000)          .build();
  httpGet.setConfig(config);
 
  | 
 
HttpClient 封装:
这里我们主要封装了无参 get 请求,其它请求请自行封装。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
   | 
 
  public class HttpUtils {
           private PoolingHttpClientConnectionManager cm;     public HttpUtils() {                  this.cm = new PoolingHttpClientConnectionManager();         this.cm.setMaxTotal(100);          this.cm.setDefaultMaxPerRoute(10);      }
           private RequestConfig getConfig() {         return RequestConfig.custom()                 .setConnectTimeout(1000)                  .setConnectionRequestTimeout(500)                  .setSocketTimeout(10*1000)                  .build();     }
           public String doGetHtml(String url) {         String html = "";                  CloseableHttpClient httpclient = HttpClients.custom()                 .setConnectionManager(this.cm).build();                  HttpGet httpGet = new HttpGet(url);                  httpGet.setConfig(getConfig());         CloseableHttpResponse response = null;         try {                          response = httpclient.execute(httpGet);                          if (response.getStatusLine().getStatusCode() == 200) {                                  HttpEntity entity = response.getEntity();                                  if (entity != null) {                     html = EntityUtils.toString(entity, "utf8");                 }             }         } catch (IOException e) { e.printStackTrace();         } finally {             if (response != null) {                 try {                     response.close();                  } catch (IOException e) {e.printStackTrace(); }             }         }         return html;     }
      
 
 
 
      public String doGetImage(String url,String path) {         String msg = "";                  CloseableHttpClient httpclient = HttpClients.custom()                 .setConnectionManager(this.cm).build();                  HttpGet httpGet = new HttpGet(url);                  httpGet.setConfig(getConfig());         CloseableHttpResponse response = null;         try {                          response = httpclient.execute(httpGet);                          if (response.getStatusLine().getStatusCode() == 200) {                                  HttpEntity entity = response.getEntity();                                  if (entity != null) {                     String suffix = url.substring(url.lastIndexOf("."));                      String imageName = UUID.randomUUID().toString()+suffix;                      File imageFile = new File(path, imageName);                      msg = imageFile.toString();                      OutputStream image = new FileOutputStream(imageFile);                      entity.writeTo(image);                  }             }         } catch (IOException e) { e.printStackTrace();         } finally {             if (response != null) {                 try {                     response.close();                  } catch (IOException e) {e.printStackTrace(); }             }         }         return msg;     }
  }
 
  |