博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
http工具类
阅读量:6212 次
发布时间:2019-06-21

本文共 5827 字,大约阅读时间需要 19 分钟。

import org.apache.http.*;import org.apache.http.client.config.RequestConfig;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.conn.ConnectionKeepAliveStrategy;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;import org.apache.http.impl.client.HttpClientBuilder;import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;import org.apache.http.message.BasicNameValuePair;import org.apache.http.protocol.HttpContext;import org.apache.http.util.EntityUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.io.IOException;import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.concurrent.TimeUnit;/** * Https请求工具类 * @author DUCHONG * @since 2018-05-03 13:04:42 */public class HttpUtils {	private static Logger logger=LoggerFactory.getLogger(HttpUtils.class);    //private static final CloseableHttpClient httpclient = HttpClients.createDefault();    private static  CloseableHttpClient httpclient =null;    static {        ConnectionKeepAliveStrategy connectionKeepAliveStrategy = new ConnectionKeepAliveStrategy() {            @Override            public long getKeepAliveDuration(HttpResponse httpResponse, HttpContext httpContext) {                return 20 * 1000; // tomcat默认keepAliveTimeout为20s            }        };        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(20, TimeUnit.SECONDS);        connManager.setMaxTotal(200);        connManager.setDefaultMaxPerRoute(200);        RequestConfig requestConfig = RequestConfig.custom()                .setConnectTimeout(10 * 1000)                .setSocketTimeout(10 * 1000)                .setConnectionRequestTimeout(10 * 1000)                .build();        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();        httpClientBuilder.setConnectionManager(connManager);        httpClientBuilder.setDefaultRequestConfig(requestConfig);        httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler());        httpClientBuilder.setKeepAliveStrategy(connectionKeepAliveStrategy);        //HttpClient httpClient = httpClientBuilder.build();        httpclient=httpClientBuilder.build();    }    /**     * 发送HttpGet请求     * @param url     * @return     */    public static String sendGet(String url) {        HttpGet httpget = new HttpGet(url);        CloseableHttpResponse response = null;        try {            response = httpclient.execute(httpget);        } catch (IOException e1) {            e1.printStackTrace();        }        String result = null;        try {            HttpEntity entity = response.getEntity();            if (entity != null) {                result = EntityUtils.toString(entity);            }        } catch (ParseException | IOException e) {            e.printStackTrace();        } finally {            try {                response.close();            } catch (IOException e) {                e.printStackTrace();            }        }        return result;    }    /**     * 发送HttpPost请求,参数为map     * @param url     * @param map     * @return     */    public static String sendPost(String url, Map
map) { List
formParams = new ArrayList
(); for (Map.Entry
entry : map.entrySet()) { formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8); HttpPost httppost = new HttpPost(url); httppost.setEntity(entity); CloseableHttpResponse response = null; try { response = httpclient.execute(httppost); } catch (IOException e) { e.printStackTrace(); } HttpEntity entity1 = response.getEntity(); String result = null; try { result = EntityUtils.toString(entity1); } catch (ParseException | IOException e) { e.printStackTrace(); } return result; } /** * 发送不带参数的HttpPost请求 * @param url * @return */ public static String sendPost(String url) { HttpPost httppost = new HttpPost(url); CloseableHttpResponse response = null; try { response = httpclient.execute(httppost); } catch (IOException e) { e.printStackTrace(); } HttpEntity entity = response.getEntity(); String result = null; try { result = EntityUtils.toString(entity); } catch (ParseException | IOException e) { e.printStackTrace(); } return result; } /** * 编码 * @param bstr * @return String */ public static String encode(byte[] bstr){ return new sun.misc.BASE64Encoder().encode(bstr); } /** * 解码 * @param str * @return string */ public static byte[] decode(String str){ byte[] bt = null; try { sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder(); bt = decoder.decodeBuffer( str ); } catch (IOException e) { e.printStackTrace(); } return bt; }}
  
org.apache.httpcomponents
httpclient
4.4
org.apache.httpcomponents
httpcore
4.4

  Commons的HttpClient项目现在是生命的尽头,不再被开发。它已取代由Apache HttpComponents项目HttpClient和的HttpCore模组,提供更好的性能和更大的灵活性。

转载于:https://www.cnblogs.com/geekdc/p/9235125.html

你可能感兴趣的文章
LightOJ 1277 Looking for a Subsequence(LIS)
查看>>
用C读取json文件
查看>>
IIS负载均衡-Application Request Route详解第四篇:使用ARR实现三层部署架构
查看>>
在ASP.NET非MVC环境中(WebForm中)构造MVC的URL参数,以及如何根据URL解析出匹配到MVC路由的Controller和Action...
查看>>
二叉树的建树,按层遍历,结点总数,页结点,深度以及三序非递归遍历二叉树,建立中序线索二叉树...
查看>>
Linux 内核动态函数调用可视化工具
查看>>
MySQL性能优化
查看>>
log4cplus使用
查看>>
正确的使用枚举(Enum)
查看>>
Web API应用架构设计分析(1)
查看>>
Java时间操作(一):关于UTC格式时间处理
查看>>
威佐夫博弈模板
查看>>
mysql show variables系统变量详解
查看>>
JAVASCRIPT中的THIS指向问题
查看>>
c语言中使用宏,需要注意的的几点
查看>>
公钥,私钥和数字签名这样最好理解
查看>>
void与void*详解
查看>>
C++ 类的静态成员及静态成员函数
查看>>
DirectStream、Stream的区别-SparkStreaming源码分析02
查看>>
SVM相关知识及和softmax区别
查看>>