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

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.util.Iterator;
      6 import java.util.List;
      7 import java.util.Map;
      8
      9 import org.apache.http.HttpEntity;
     10 import org.apache.http.HttpStatus;
     11 import org.apache.http.client.config.RequestConfig;
     12 import org.apache.http.client.methods.CloseableHttpResponse;
     13 import org.apache.http.client.methods.HttpGet;
     14 import org.apache.http.client.methods.HttpPost;
     15 import org.apache.http.entity.ContentType;
     16 import org.apache.http.entity.StringEntity;
     17 import org.apache.http.entity.mime.MultipartEntityBuilder;
     18 import org.apache.http.entity.mime.content.FileBody;
     19 import org.apache.http.entity.mime.content.StringBody;
     20 import org.apache.http.impl.client.CloseableHttpClient;
     21 import org.apache.http.impl.client.HttpClientBuilder;
     22 import org.apache.http.impl.client.HttpClients;
     23 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
     24 import org.apache.http.util.EntityUtils;
     25
     26 /**
     27  *
     28  * @author H__D
     29  * @date 2016年10月19日 上午11:27:25
     30  *
     31  */
     32 public class HttpClientUtil {
     33
     34     // utf-8字符编码
     35     public static final String CHARSET_UTF_8 = "utf-8";
     36
     37     // HTTP内容类型。
     38     public static final String CONTENT_TYPE_TEXT_HTML = "text/xml";
     39
     40     // HTTP内容类型。相当于form表单的形式,提交数据
     41     public static final String CONTENT_TYPE_FORM_URL = "application/x-www-form-urlencoded";
     42
     43     // HTTP内容类型。相当于form表单的形式,提交数据
     44     public static final String CONTENT_TYPE_JSON_URL = "application/json;charset=utf-8";
     45
     46
     47     // 连接管理器
     48     private static PoolingHttpClientConnectionManager pool;
     49
     50     // 请求配置
     51     private static RequestConfig requestConfig;
     52
     53     static {
     54         pool = new PoolingHttpClientConnectionManager();
     55         // 设置连接池的最大连接数
     56         pool.setMaxTotal(50);
     57         // 设置每个路由的最大连接数,默认是2
     58         pool.setDefaultMaxPerRoute(5);
     59
     60         // 设置请求超时时间
     61         requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(50000)
     62                 .setConnectionRequestTimeout(50000).build();
     63     }
     64
     65     public static CloseableHttpClient getHttpClient() {
     66         // 从连接池中获取httpclient
     67         return HttpClientBuilder.create().setConnectionManager(pool).build();
     68     }
     69
     70     /**
     71      * 发送Post请求
     72      *
     73      * @param httpPost
     74      * @return
     75      */
     76     private static String sendHttpPost(HttpPost httpPost) {
     77
     78         CloseableHttpClient httpClient = null;
     79         CloseableHttpResponse response = null;
     80         // 响应内容
     81         String responseContent = null;
     82         try {
     83             // 创建默认的httpClient实例.
     84             httpClient = HttpClients.createDefault();
     85             // 配置请求信息
     86             httpPost.setConfig(requestConfig);
     87             // 执行请求
     88             response = httpClient.execute(httpPost);
     89             // 得到响应实例
     90             HttpEntity entity = response.getEntity();
     91
     92             // 可以获得响应头
     93             // Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
     94             // for (Header header : headers) {
     95             // System.out.println(header.getName());
     96             // }
     97
     98             // 得到响应类型
     99             // System.out.println(ContentType.getOrDefault(response.getEntity()).getMimeType());
    100
    101             // 判断响应状态
    102             if (response.getStatusLine().getStatusCode() >= 300) {
    103                 throw new Exception(
    104                         "HTTP Request is not success, Response code is " + response.getStatusLine().getStatusCode());
    105             }
    106
    107             if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
    108                 responseContent = EntityUtils.toString(entity, CHARSET_UTF_8);
    109             }
    110
    111         } catch (Exception e) {
    112             e.printStackTrace();
    113         } finally {
    114             try {
    115                 // 关闭连接,释放资源
    116                 if (response != null) {
    117                     response.close();
    118                 }
    119                 if (httpClient != null) {
    120                     httpClient.close();
    121                 }
    122             } catch (IOException e) {
    123                 e.printStackTrace();
    124             }
    125         }
    126         return responseContent;
    127     }
    128
    129     /**
    130      * 发送Get请求
    131      *
    132      * @param httpGet
    133      * @return
    134      */
    135     private static String sendHttpGet(HttpGet httpGet) {
    136
    137         CloseableHttpClient httpClient = null;
    138         CloseableHttpResponse response = null;
    139         // 响应内容
    140         String responseContent = null;
    141         try {
    142             // 创建默认的httpClient实例.
    143             httpClient = HttpClients.createDefault();
    144             // 配置请求信息
    145             httpGet.setConfig(requestConfig);
    146             // 执行请求
    147             response = httpClient.execute(httpGet);
    148             // 得到响应实例
    149             HttpEntity entity = response.getEntity();
    150
    151             // 可以获得响应头
    152             // Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
    153             // for (Header header : headers) {
    154             // System.out.println(header.getName());
    155             // }
    156
    157             // 得到响应类型
    158             // System.out.println(ContentType.getOrDefault(response.getEntity()).getMimeType());
    159
    160             // 判断响应状态
    161             if (response.getStatusLine().getStatusCode() >= 300) {
    162                 throw new Exception(
    163                         "HTTP Request is not success, Response code is " + response.getStatusLine().getStatusCode());
    164             }
    165
    166             if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
    167                 responseContent = EntityUtils.toString(entity, CHARSET_UTF_8);
    168             }
    169
    170         } catch (Exception e) {
    171             e.printStackTrace();
    172         } finally {
    173             try {
    174                 // 关闭连接,释放资源
    175                 if (response != null) {
    176                     response.close();
    177                 }
    178                 if (httpClient != null) {
    179                     httpClient.close();
    180                 }
    181             } catch (IOException e) {
    182                 e.printStackTrace();
    183             }
    184         }
    185         return responseContent;
    186     }
    187
    188
    189
    190     /**
    191      * 发送 post请求
    192      *
    193      * @param httpUrl
    194      *            地址
    195      */
    196     public static String sendHttpPost(String httpUrl) {
    197         // 创建httpPost
    198         HttpPost httpPost = new HttpPost(httpUrl);
    199         return sendHttpPost(httpPost);
    200     }
    201
    202     /**
    203      * 发送 get请求
    204      *
    205      * @param httpUrl
    206      */
    207     public static String sendHttpGet(String httpUrl) {
    208         // 创建get请求
    209         HttpGet httpGet = new HttpGet(httpUrl);
    210         return sendHttpGet(httpGet);
    211     }
    212
    213
    214
    215     /**
    216      * 发送 post请求(带文件)
    217      *
    218      * @param httpUrl
    219      *            地址
    220      * @param maps
    221      *            参数
    222      * @param fileLists
    223      *            附件
    224      */
    225     public static String sendHttpPost(String httpUrl, Map<String, String> maps, List<File> fileLists) {
    226         HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
    227         MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
    228         if (maps != null) {
    229             for (String key : maps.keySet()) {
    230                 meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.TEXT_PLAIN));
    231             }
    232         }
    233         if (fileLists != null) {
    234             for (File file : fileLists) {
    235                 FileBody fileBody = new FileBody(file);
    236                 meBuilder.addPart("files", fileBody);
    237             }
    238         }
    239         HttpEntity reqEntity = meBuilder.build();
    240         httpPost.setEntity(reqEntity);
    241         return sendHttpPost(httpPost);
    242     }
    243
    244     /**
    245      * 发送 post请求
    246      *
    247      * @param httpUrl
    248      *            地址
    249      * @param params
    250      *            参数(格式:key1=value1&key2=value2)
    251      *
    252      */
    253     public static String sendHttpPost(String httpUrl, String params) {
    254         HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
    255         try {
    256             // 设置参数
    257             if (params != null && params.trim().length() > 0) {
    258                 StringEntity stringEntity = new StringEntity(params, "UTF-8");
    259                 stringEntity.setContentType(CONTENT_TYPE_FORM_URL);
    260                 httpPost.setEntity(stringEntity);
    261             }
    262         } catch (Exception e) {
    263             e.printStackTrace();
    264         }
    265         return sendHttpPost(httpPost);
    266     }
    267
    268     /**
    269      * 发送 post请求
    270      *
    271      * @param maps
    272      *            参数
    273      */
    274     public static String sendHttpPost(String httpUrl, Map<String, String> maps) {
    275         String parem = convertStringParamter(maps);
    276         return sendHttpPost(httpUrl, parem);
    277     }
    278
    279
    280
    281
    282     /**
    283      * 发送 post请求 发送json数据
    284      *
    285      * @param httpUrl
    286      *            地址
    287      * @param paramsJson
    288      *            参数(格式 json)
    289      *
    290      */
    291     public static String sendHttpPostJson(String httpUrl, String paramsJson) {
    292         HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
    293         try {
    294             // 设置参数
    295             if (paramsJson != null && paramsJson.trim().length() > 0) {
    296                 StringEntity stringEntity = new StringEntity(paramsJson, "UTF-8");
    297                 stringEntity.setContentType(CONTENT_TYPE_JSON_URL);
    298                 httpPost.setEntity(stringEntity);
    299             }
    300         } catch (Exception e) {
    301             e.printStackTrace();
    302         }
    303         return sendHttpPost(httpPost);
    304     }
    305
    306     /**
    307      * 发送 post请求 发送xml数据
    308      *
    309      * @param httpUrl   地址
    310      * @param paramsXml  参数(格式 Xml)
    311      *
    312      */
    313     public static String sendHttpPostXml(String httpUrl, String paramsXml) {
    314         HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
    315         try {
    316             // 设置参数
    317             if (paramsXml != null && paramsXml.trim().length() > 0) {
    318                 StringEntity stringEntity = new StringEntity(paramsXml, "UTF-8");
    319                 stringEntity.setContentType(CONTENT_TYPE_TEXT_HTML);
    320                 httpPost.setEntity(stringEntity);
    321             }
    322         } catch (Exception e) {
    323             e.printStackTrace();
    324         }
    325         return sendHttpPost(httpPost);
    326     }
    327
    328
    329     /**
    330      * 将map集合的键值对转化成:key1=value1&key2=value2 的形式
    331      *
    332      * @param parameterMap
    333      *            需要转化的键值对集合
    334      * @return 字符串
    335      */
    336     public static String convertStringParamter(Map parameterMap) {
    337         StringBuffer parameterBuffer = new StringBuffer();
    338         if (parameterMap != null) {
    339             Iterator iterator = parameterMap.keySet().iterator();
    340             String key = null;
    341             String value = null;
    342             while (iterator.hasNext()) {
    343                 key = (String) iterator.next();
    344                 if (parameterMap.get(key) != null) {
    345                     value = (String) parameterMap.get(key);
    346                 } else {
    347                     value = "";
    348                 }
    349                 parameterBuffer.append(key).append("=").append(value);
    350                 if (iterator.hasNext()) {
    351                     parameterBuffer.append("&");
    352                 }
    353             }
    354         }
    355         return parameterBuffer.toString();
    356     }
    357
    358     public static void main(String[] args) throws Exception {
    359
    360         System.out.println(sendHttpGet("http://www.baidu.com"));
    361     }
    362 }

      

时间: 2024-08-25 20:44:08

【JAVA】通过HttpClient发送HTTP请求的方法的相关文章

通过java.net.URLConnection发送HTTP请求的方法

1.GET与POST请求的区别 a) get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet, b) post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内. 2.URLConnection的对象 a) 获取URLConnection实例 URL url = new URL(urlString); // 根据url生成urlConnection对象 urlConnection = (HttpURLConnection) url.

使用httpclient实现http链接池与使用HttpURLConnection发送http请求的方法与性能对比

使用httpclient实现http链接池与使用HttpURLConnection发送http请求的方法与性能对比 在项目中需要使用http调用接口,实现了两套发送http请求的方法,一个是使用apache的httpclient提供的http链接池来发送http请求,另一个是使用java原生的HttpURLConnection来发送http请求,并对两者性能进行了对比. 使用httpclient中的链接池发送http请求 使用最新的4.5.2版httpclient进行实现.在maven中引入 <

Android系列之网络(三)----使用HttpClient发送HTTP请求(分别通过GET和POST方法发送数据)

[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4006009.html 联系方式:[email protected] [系列]Android系列之网络:(持续更新) Android系列之网络(一)----使用HttpClient发送HTTP请求(通过get方法获取数据) Android系列之网络(二)----HTTP请求头与响应头 Android

JAVA利用HttpClient进行POST请求(HTTPS)

目前,要为另一个项目提供接口,接口是用HTTP URL实现的,最初的想法是另一个项目用jQuery post进行请求. 但是,很可能另一个项目是部署在别的机器上,那么就存在跨域问题,而JQuery的post请求是不允许跨域的. 这时,就只能够用HttpClient包进行请求了,同时由于请求的URL是HTTPS的,为了避免需要证书,所以用一个类继承DefaultHttpClient类,忽略校验过程. 1.写一个SSLClient类,继承至HttpClient [java] view plain c

android使用apache httpclient发送post请求

package com.liuc; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.ht

HTTPClient 发送HTTPS请求

HTTPClient 发送HTTP请求就不多说了, 现在给出发送HTTPS请求, 主要思路是忽略证书验证. /** * * @param url * @param contextType "image/jpeg","application/Json" * @return */ public static byte[] sendHttpsGetUrl(HttpClient httpClient1 ,String url,String contextType) { //

使用httpclient发送http请求

先来个httpclient的maven依赖 <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3</version> </dependency> SimpleHttpClient.java package com.openapi.TestPojo; im

java使用httpcomponents发送get请求

一.适用场景 在ESTful webservice中,get方法一般都是用来获取数据.我们可以使用httpcomponents组件来完成调用. 如我们需要发起get请求,携带的参数都是附加到请求的url后面. url:"http://www.xxxxx.com/message?id=000010" 二.代码示例 1 package com.demo.test; 2 3 import java.io.IOException; 4 5 import org.apache.http.Http

.net core使用HttpClient发送代理请求_程序内抓包_Fiddler抓包

原文:.net core使用HttpClient发送代理请求_程序内抓包_Fiddler抓包 前言:  通过Fiddler抓取浏览器请求数据,相信大家已经都会用了,我们知道Fiddler是通过在本机计算器添加一个默认的代理服务器来实现的抓包数据的,端口号为:8888. 其实当我们打开Fiddler的设置也可以看到: 然后查看本地计算器的网络代理设置: 基于上面的原理,Fiddler就实现了经过本机计算器请求的数据抓包了... 那么,我们通过C#代码,在.net Core中使用HttpClient