【JAVA】通过HttpClient发送HTTP请求的方法

来源:互联网 发布:mysql session 编辑:程序博客网 时间:2024/05/23 13:50

HttpClient介绍

  HttpClient 不是一个浏览器。它是一个客户端的 HTTP 通信实现库。HttpClient的目标是发 送和接收HTTP 报文。HttpClient不会去缓存内容,执行 嵌入在 HTML 页面中的javascript 代码,猜测内容类型,重新格式化请求/重定向URI,或者其它和 HTTP 运输无关的功能。

HttpClient使用

  •   使用需要引入jar包,maven项目引入如下:
    复制代码
     1         <dependency> 2             <groupId>org.apache.httpcomponents</groupId> 3             <artifactId>httpclient</artifactId> 4             <version>4.5</version> 5         </dependency> 6  7         <dependency> 8             <groupId>org.apache.httpcomponents</groupId> 9             <artifactId>httpcore</artifactId>10             <version>4.4.4</version>11         </dependency>12 13         <dependency>14             <groupId>org.apache.httpcomponents</groupId>15             <artifactId>httpmime</artifactId>16             <version>4.5</version>17         </dependency>
    复制代码

     

  •   使用方法,代码如下: 
    复制代码
      1 package com.test;  2   3 import java.io.File;  4 import java.io.IOException;  5 import java.security.KeyManagementException;  6 import java.security.KeyStoreException;  7 import java.security.NoSuchAlgorithmException;  8 import java.util.Iterator;  9 import java.util.List; 10 import java.util.Map; 11  12 import org.apache.http.HttpEntity; 13 import org.apache.http.HttpStatus; 14 import org.apache.http.client.config.RequestConfig; 15 import org.apache.http.client.methods.CloseableHttpResponse; 16 import org.apache.http.client.methods.HttpGet; 17 import org.apache.http.client.methods.HttpPost; 18 import org.apache.http.config.Registry; 19 import org.apache.http.config.RegistryBuilder; 20 import org.apache.http.conn.socket.ConnectionSocketFactory; 21 import org.apache.http.conn.socket.PlainConnectionSocketFactory; 22 import org.apache.http.conn.ssl.SSLConnectionSocketFactory; 23 import org.apache.http.conn.ssl.SSLContextBuilder; 24 import org.apache.http.conn.ssl.TrustSelfSignedStrategy; 25 import org.apache.http.entity.ContentType; 26 import org.apache.http.entity.StringEntity; 27 import org.apache.http.entity.mime.MultipartEntityBuilder; 28 import org.apache.http.entity.mime.content.FileBody; 29 import org.apache.http.entity.mime.content.StringBody; 30 import org.apache.http.impl.client.CloseableHttpClient; 31 import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; 32 import org.apache.http.impl.client.HttpClients; 33 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; 34 import org.apache.http.util.EntityUtils; 35  36 /** 37  *  38  * @author H__D 39  * @date 2016年10月19日 上午11:27:25 40  * 41  */ 42 public class HttpClientUtil { 43  44     // utf-8字符编码 45     public static final String CHARSET_UTF_8 = "utf-8"; 46  47     // HTTP内容类型。 48     public static final String CONTENT_TYPE_TEXT_HTML = "text/xml"; 49  50     // HTTP内容类型。相当于form表单的形式,提交数据 51     public static final String CONTENT_TYPE_FORM_URL = "application/x-www-form-urlencoded"; 52  53     // HTTP内容类型。相当于form表单的形式,提交数据 54     public static final String CONTENT_TYPE_JSON_URL = "application/json;charset=utf-8"; 55      56  57     // 连接管理器 58     private static PoolingHttpClientConnectionManager pool; 59  60     // 请求配置 61     private static RequestConfig requestConfig; 62  63     static { 64          65         try { 66             //System.out.println("初始化HttpClientTest~~~开始"); 67             SSLContextBuilder builder = new SSLContextBuilder(); 68             builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); 69             SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( 70                     builder.build()); 71             // 配置同时支持 HTTP 和 HTPPS 72             Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create().register( 73                     "http", PlainConnectionSocketFactory.getSocketFactory()).register( 74                     "https", sslsf).build(); 75             // 初始化连接管理器 76             pool = new PoolingHttpClientConnectionManager( 77                     socketFactoryRegistry); 78             // 将最大连接数增加到200,实际项目最好从配置文件中读取这个值 79             pool.setMaxTotal(200); 80             // 设置最大路由 81             pool.setDefaultMaxPerRoute(2); 82             // 根据默认超时限制初始化requestConfig 83             int socketTimeout = 10000; 84             int connectTimeout = 10000; 85             int connectionRequestTimeout = 10000; 86             requestConfig = RequestConfig.custom().setConnectionRequestTimeout( 87                     connectionRequestTimeout).setSocketTimeout(socketTimeout).setConnectTimeout( 88                     connectTimeout).build(); 89  90             //System.out.println("初始化HttpClientTest~~~结束"); 91         } catch (NoSuchAlgorithmException e) { 92             e.printStackTrace(); 93         } catch (KeyStoreException e) { 94             e.printStackTrace(); 95         } catch (KeyManagementException e) { 96             e.printStackTrace(); 97         } 98          99 100         // 设置请求超时时间101         requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(50000)102                 .setConnectionRequestTimeout(50000).build();103     }104 105     public static CloseableHttpClient getHttpClient() {106         107         CloseableHttpClient httpClient = HttpClients.custom()108                 // 设置连接池管理109                 .setConnectionManager(pool)110                 // 设置请求配置111                 .setDefaultRequestConfig(requestConfig)112                 // 设置重试次数113                 .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))114                 .build();115         116         return httpClient;117     }118 119     /**120      * 发送Post请求121      * 122      * @param httpPost123      * @return124      */125     private static String sendHttpPost(HttpPost httpPost) {126 127         CloseableHttpClient httpClient = null;128         CloseableHttpResponse response = null;129         // 响应内容130         String responseContent = null;131         try {132             // 创建默认的httpClient实例.133             httpClient = getHttpClient();134             // 配置请求信息135             httpPost.setConfig(requestConfig);136             // 执行请求137             response = httpClient.execute(httpPost);138             // 得到响应实例139             HttpEntity entity = response.getEntity();140 141             // 可以获得响应头142             // Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);143             // for (Header header : headers) {144             // System.out.println(header.getName());145             // }146 147             // 得到响应类型148             // System.out.println(ContentType.getOrDefault(response.getEntity()).getMimeType());149 150             // 判断响应状态151             if (response.getStatusLine().getStatusCode() >= 300) {152                 throw new Exception(153                         "HTTP Request is not success, Response code is " + response.getStatusLine().getStatusCode());154             }155 156             if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {157                 responseContent = EntityUtils.toString(entity, CHARSET_UTF_8);158                 EntityUtils.consume(entity);159             }160 161         } catch (Exception e) {162             e.printStackTrace();163         } finally {164             try {165                 // 释放资源166                 if (response != null) {167                     response.close();168                 }169             } catch (IOException e) {170                 e.printStackTrace();171             }172         }173         return responseContent;174     }175 176     /**177      * 发送Get请求178      * 179      * @param httpGet180      * @return181      */182     private static String sendHttpGet(HttpGet httpGet) {183 184         CloseableHttpClient httpClient = null;185         CloseableHttpResponse response = null;186         // 响应内容187         String responseContent = null;188         try {189             // 创建默认的httpClient实例.190             httpClient = getHttpClient();191             // 配置请求信息192             httpGet.setConfig(requestConfig);193             // 执行请求194             response = httpClient.execute(httpGet);195             // 得到响应实例196             HttpEntity entity = response.getEntity();197 198             // 可以获得响应头199             // Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);200             // for (Header header : headers) {201             // System.out.println(header.getName());202             // }203 204             // 得到响应类型205             // System.out.println(ContentType.getOrDefault(response.getEntity()).getMimeType());206 207             // 判断响应状态208             if (response.getStatusLine().getStatusCode() >= 300) {209                 throw new Exception(210                         "HTTP Request is not success, Response code is " + response.getStatusLine().getStatusCode());211             }212 213             if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {214                 responseContent = EntityUtils.toString(entity, CHARSET_UTF_8);215                 EntityUtils.consume(entity);216             }217 218         } catch (Exception e) {219             e.printStackTrace();220         } finally {221             try {222                 // 释放资源223                 if (response != null) {224                     response.close();225                 }226             } catch (IOException e) {227                 e.printStackTrace();228             }229         }230         return responseContent;231     }232     233     234     235     /**236      * 发送 post请求237      * 238      * @param httpUrl239      *            地址240      */241     public static String sendHttpPost(String httpUrl) {242         // 创建httpPost243         HttpPost httpPost = new HttpPost(httpUrl);244         return sendHttpPost(httpPost);245     }246 247     /**248      * 发送 get请求249      * 250      * @param httpUrl251      */252     public static String sendHttpGet(String httpUrl) {253         // 创建get请求254         HttpGet httpGet = new HttpGet(httpUrl);255         return sendHttpGet(httpGet);256     }257     258     259 260     /**261      * 发送 post请求(带文件)262      * 263      * @param httpUrl264      *            地址265      * @param maps266      *            参数267      * @param fileLists268      *            附件269      */270     public static String sendHttpPost(String httpUrl, Map<String, String> maps, List<File> fileLists) {271         HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost272         MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();273         if (maps != null) {274             for (String key : maps.keySet()) {275                 meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.TEXT_PLAIN));276             }277         }278         if (fileLists != null) {279             for (File file : fileLists) {280                 FileBody fileBody = new FileBody(file);281                 meBuilder.addPart("files", fileBody);282             }283         }284         HttpEntity reqEntity = meBuilder.build();285         httpPost.setEntity(reqEntity);286         return sendHttpPost(httpPost);287     }288 289     /**290      * 发送 post请求291      * 292      * @param httpUrl293      *            地址294      * @param params295      *            参数(格式:key1=value1&key2=value2)296      * 297      */298     public static String sendHttpPost(String httpUrl, String params) {299         HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost300         try {301             // 设置参数302             if (params != null && params.trim().length() > 0) {303                 StringEntity stringEntity = new StringEntity(params, "UTF-8");304                 stringEntity.setContentType(CONTENT_TYPE_FORM_URL);305                 httpPost.setEntity(stringEntity);306             }307         } catch (Exception e) {308             e.printStackTrace();309         }310         return sendHttpPost(httpPost);311     }312 313     /**314      * 发送 post请求315      * 316      * @param maps317      *            参数318      */319     public static String sendHttpPost(String httpUrl, Map<String, String> maps) {320         String parem = convertStringParamter(maps);321         return sendHttpPost(httpUrl, parem);322     }323 324     325     326     327     /**328      * 发送 post请求 发送json数据329      * 330      * @param httpUrl331      *            地址332      * @param paramsJson333      *            参数(格式 json)334      * 335      */336     public static String sendHttpPostJson(String httpUrl, String paramsJson) {337         HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost338         try {339             // 设置参数340             if (paramsJson != null && paramsJson.trim().length() > 0) {341                 StringEntity stringEntity = new StringEntity(paramsJson, "UTF-8");342                 stringEntity.setContentType(CONTENT_TYPE_JSON_URL);343                 httpPost.setEntity(stringEntity);344             }345         } catch (Exception e) {346             e.printStackTrace();347         }348         return sendHttpPost(httpPost);349     }350     351     /**352      * 发送 post请求 发送xml数据353      * 354      * @param httpUrl   地址355      * @param paramsXml  参数(格式 Xml)356      * 357      */358     public static String sendHttpPostXml(String httpUrl, String paramsXml) {359         HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost360         try {361             // 设置参数362             if (paramsXml != null && paramsXml.trim().length() > 0) {363                 StringEntity stringEntity = new StringEntity(paramsXml, "UTF-8");364                 stringEntity.setContentType(CONTENT_TYPE_TEXT_HTML);365                 httpPost.setEntity(stringEntity);366             }367         } catch (Exception e) {368             e.printStackTrace();369         }370         return sendHttpPost(httpPost);371     }372     373 374     /**375      * 将map集合的键值对转化成:key1=value1&key2=value2 的形式376      * 377      * @param parameterMap378      *            需要转化的键值对集合379      * @return 字符串380      */381     public static String convertStringParamter(Map parameterMap) {382         StringBuffer parameterBuffer = new StringBuffer();383         if (parameterMap != null) {384             Iterator iterator = parameterMap.keySet().iterator();385             String key = null;386             String value = null;387             while (iterator.hasNext()) {388                 key = (String) iterator.next();389                 if (parameterMap.get(key) != null) {390                     value = (String) parameterMap.get(key);391                 } else {392                     value = "";393                 }394                 parameterBuffer.append(key).append("=").append(value);395                 if (iterator.hasNext()) {396                     parameterBuffer.append("&");397                 }398             }399         }400         return parameterBuffer.toString();401     }402 403     public static void main(String[] args) throws Exception {404         405         System.out.println(sendHttpGet("http://www.baidu.com"));406     407     }408 }
    复制代码
阅读全文
0 0