• JAVA API about HTTP 3


      1 package com.han.http;
      2 
      3 
      4 import java.io.IOException;
      5 import java.io.UnsupportedEncodingException;
      6 import java.nio.charset.Charset;
      7 import java.util.ArrayList;
      8 import java.util.HashMap;
      9 import java.util.List;
     10 import java.util.Map;
     11 
     12 import org.apache.http.HttpEntity;
     13 import org.apache.http.HttpResponse;
     14 import org.apache.http.NameValuePair;
     15 import org.apache.http.client.ClientProtocolException;
     16 import org.apache.http.client.ResponseHandler;
     17 import org.apache.http.client.config.CookieSpecs;
     18 import org.apache.http.client.config.RequestConfig;
     19 import org.apache.http.client.entity.UrlEncodedFormEntity;
     20 import org.apache.http.client.methods.CloseableHttpResponse;
     21 import org.apache.http.client.methods.HttpGet;
     22 import org.apache.http.client.methods.HttpPost;
     23 import org.apache.http.client.protocol.HttpClientContext;
     24 import org.apache.http.entity.StringEntity;
     25 import org.apache.http.impl.client.CloseableHttpClient;
     26 import org.apache.http.impl.client.HttpClientBuilder;
     27 import org.apache.http.impl.client.HttpClients;
     28 import org.apache.http.message.BasicHeader;
     29 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
     30 import org.apache.http.message.BasicNameValuePair;
     31 import org.apache.http.util.EntityUtils;
     32 import org.slf4j.Logger;
     33 import org.slf4j.LoggerFactory;
     34 
     35 
     36 public class HttpClientHelp {
     37 
     38     private final static Logger logger = LoggerFactory.getLogger(HttpClientHelp.class);
     39 
     40     private final static String ENCODE = "utf-8";
     41 
     42     private final static Charset CHARSET = Charset.forName("utf-8");
     43     public static final int TIMEOUT = 20000;
     44 
     45     private static PoolingHttpClientConnectionManager cm = null;
     46     private static RequestConfig defaultRequestConfig = null;
     47 
     48     static {
     49         /**
     50          * 连接池管理
     51          * **/
     52         cm = new PoolingHttpClientConnectionManager(); // 将最大连接数
     53         cm.setMaxTotal(50);
     54         // 将每个路由基础的连接增加到20
     55         cm.setDefaultMaxPerRoute(20);
     56 
     57         /** request设置 **/
     58         // 连接超时 20s
     59         defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).setRedirectsEnabled(false).setSocketTimeout(TIMEOUT)
     60                 .setConnectTimeout(TIMEOUT).setConnectionRequestTimeout(TIMEOUT).build();
     61     }
     62     
     63     public static CloseableHttpClient getClient() {
     64         return HttpClientBuilder.create().setDefaultRequestConfig(defaultRequestConfig).setConnectionManager(cm).build();
     65     }
     66     
     67     
     68     public static String httpGetByUrl(String url) throws ClientProtocolException, IOException {
     69         String responseBody = "";
     70         CloseableHttpClient httpclient = HttpClients.createDefault();
     71         try {
     72             HttpGet httpget = new HttpGet(url);
     73             ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
     74                 @Override
     75                 public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
     76                     int status = response.getStatusLine().getStatusCode();
     77                     if (status >= 200 && status < 300) {
     78                         HttpEntity entity = response.getEntity();
     79                         return entity != null ? EntityUtils.toString(entity) : null;
     80                     } else {
     81                         throw new ClientProtocolException("Unexpected response status: " + status);
     82                     }
     83                 }
     84             };
     85             responseBody = httpclient.execute(httpget, responseHandler);
     86         } finally {
     87             httpclient.close();
     88         }
     89         return responseBody;
     90     }
     91 
     92     public static String postBodyContent(String url, String bodyContent) throws ClientProtocolException, IOException {
     93         String result = "";
     94         CloseableHttpClient httpclient = HttpClients.createDefault();
     95         CloseableHttpResponse response = null;
     96         try {
     97             HttpPost httppost = new HttpPost(url);
     98             StringEntity reqEntity = new StringEntity(bodyContent, "UTF-8");
     99             httppost.setEntity(reqEntity);
    100             // 设置连接超时5秒,请求超时1秒,返回数据超时8秒
    101             RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(1000).setSocketTimeout(8000)
    102                     .build();
    103             httppost.setConfig(requestConfig);
    104             response = httpclient.execute(httppost);
    105             HttpEntity responseEntity = response.getEntity();
    106             byte[] bytes = EntityUtils.toByteArray(responseEntity);
    107             result = new String(bytes, "UTF-8");
    108         } finally {
    109             if (null != response) {
    110                 response.close();
    111             }
    112             httpclient.close();
    113         }
    114         return result;
    115     }
    116     
    117 
    118 
    119     /**
    120      * post paramMap
    121      * 
    122      * @param path
    123      * @param params
    124      * @param headers
    125      * @return
    126      */
    127     public static String post(String path, Map<String, String> params, Map<String, String> headers) {
    128         List<NameValuePair> values = new ArrayList<NameValuePair>();
    129         for (String s : params.keySet()) {
    130             values.add(new BasicNameValuePair(s, params.get(s)));
    131         }
    132         UrlEncodedFormEntity entity = null;
    133         try {
    134             entity = new UrlEncodedFormEntity(values, ENCODE);
    135         } catch (UnsupportedEncodingException e) {
    136             // TODO Auto-generated catch block
    137             logger.error(e.getMessage());
    138         }
    139         return post(path, entity, headers);
    140     }
    141 
    142     /**
    143      * post body
    144      * 
    145      * @param path
    146      * @param body
    147      * @param headers
    148      * @return
    149      */
    150     public static String post(String path, String body, Map<String, String> headers) {
    151         return post(path, new StringEntity(body, CHARSET), headers);
    152     }
    153 
    154     public static String post(String path, HttpEntity postEntity, Map<String, String> headers) {
    155         String responseContent = null;
    156         CloseableHttpClient client = getClient();
    157         HttpPost httpPost = null;
    158         try {
    159             httpPost = new HttpPost(path);
    160             if (headers != null && !headers.isEmpty()) {
    161                 for (String s : headers.keySet()) {
    162                     httpPost.addHeader(s, headers.get(s));
    163                 }
    164             }
    165             httpPost.addHeader("Content-Type", "application/json");
    166             httpPost.setEntity(postEntity);
    167             CloseableHttpResponse response = client.execute(httpPost, HttpClientContext.create());
    168             HttpEntity entity = response.getEntity();
    169             responseContent = EntityUtils.toString(entity, ENCODE);
    170         } catch (Exception e) {
    171             logger.error(e.getMessage());
    172             e.printStackTrace();
    173         } finally {
    174             if (httpPost != null) {
    175                 httpPost.releaseConnection();
    176             }
    177         }
    178         return responseContent;
    179     }
    180 
    181     public static String get(String path, Map<String, String> headers) {
    182         String responseContent = null;
    183         CloseableHttpClient client = getClient();
    184         HttpGet httpGet = new HttpGet(path);
    185         try {
    186 
    187             if (headers != null && !headers.isEmpty()) {
    188                 for (String s : headers.keySet()) {
    189                     httpGet.addHeader(s, headers.get(s));
    190                 }
    191             }
    192             CloseableHttpResponse response = client.execute(httpGet, HttpClientContext.create());
    193             HttpEntity entity = response.getEntity();
    194             responseContent = EntityUtils.toString(entity, ENCODE);
    195         } catch (Exception e) {
    196             logger.error(e.getMessage());
    197             e.printStackTrace();
    198         } finally {
    199             httpGet.releaseConnection();
    200         }
    201         return responseContent;
    202     }
    203     
    204     
    205     @SuppressWarnings("deprecation")//设置了请求头
    206     public static String postByBodyStringWithHeader(String url, String bodyString) throws ClientProtocolException, IOException {
    207         String result = "";
    208         CloseableHttpClient httpclient = HttpClients.createDefault();
    209         CloseableHttpResponse response = null; 
    210         try {
    211             HttpPost httppost = new HttpPost(url);
    212             StringEntity reqEntity = new StringEntity(bodyString, "UTF-8");
    213             httppost.setEntity(reqEntity);
    214             
    215             Map<String, String> headers = new HashMap<String, String>();
    216             headers.put("Content-Type", "application/json;charset=UTF-8");
    217             if (headers != null && !headers.isEmpty()) {
    218                 for (String s : headers.keySet()) {
    219                     httppost.addHeader(s, headers.get(s));
    220                 }
    221             }
    222             //设置连接超时5秒,请求超时1秒,返回数据超时8秒
    223 //            RequestConfig requestConfig = RequestConfig.custom()  
    224 //                    .setConnectTimeout(5000).setConnectionRequestTimeout(5000)  
    225 //                    .setSocketTimeout(8000).build(); 
    226 //            httppost.setConfig(requestConfig);
    227             response = httpclient.execute(httppost);
    228             HttpEntity responseEntity = response.getEntity();
    229             byte[] bytes = EntityUtils.toByteArray(responseEntity);
    230             result = new String(bytes,"UTF-8");
    231         } finally {
    232             if (null != response) {
    233                 response.close();
    234             }
    235             httpclient.close();
    236         }
    237         return result;
    238     }
    239     
    240     @SuppressWarnings("deprecation")//没有设置请求头
    241     public static String postByBodyString(String url, String bodyString) throws ClientProtocolException, IOException {
    242         String result = "";
    243         CloseableHttpClient httpclient = HttpClients.createDefault();
    244         CloseableHttpResponse response = null; 
    245         try {
    246             HttpPost httppost = new HttpPost(url);
    247             StringEntity reqEntity = new StringEntity(bodyString, "UTF-8");
    248             httppost.setEntity(reqEntity);
    249             
    250             //设置连接超时5秒,请求超时1秒,返回数据超时8秒
    251 //            RequestConfig requestConfig = RequestConfig.custom()  
    252 //                    .setConnectTimeout(5000).setConnectionRequestTimeout(5000)  
    253 //                    .setSocketTimeout(8000).build(); 
    254 //            httppost.setConfig(requestConfig);
    255             response = httpclient.execute(httppost);
    256             HttpEntity responseEntity = response.getEntity();
    257             byte[] bytes = EntityUtils.toByteArray(responseEntity);
    258             result = new String(bytes,"UTF-8");
    259         } finally {
    260             if (null != response) {
    261                 response.close();
    262             }
    263             httpclient.close();
    264         }
    265         return result;
    266     }
    267     
    268     
    269 }
  • 相关阅读:
    Mycat读写分离+高可用笔记
    MyCAT基础安装笔记
    C# Winform中DataGridView的DataGridViewCheckBoxColumn CheckBox选中判断
    C# winform DataTable 批量数据处理 增、删、改 .
    选中CheckBoxList的值放到TextBox中,再次选中从textBox中删除
    dede后台删除文章后台还有分页显示解决方法
    dedecms数据库表说明大全
    织梦自增函数[field:global name=autoindex/]常见用法
    http协议的状态码——400,401,403,404,500,502,503,301,302等常见网页错误代码
    web.config设置之system.webServer 详细介绍,为网站设置默认文档
  • 原文地址:https://www.cnblogs.com/stronghan/p/6170805.html
Copyright © 2020-2023  润新知