博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
封装HttpClient进行http请求与https请求
阅读量:6265 次
发布时间:2019-06-22

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

一.https忽略证书

/** * 用于进行Https请求的HttpClient *  * @author joey * */public class SSLClient {    public static CloseableHttpClient createSSLClientDefault(){        try {            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {                //信任所有                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {                    return true;                }            }).build();            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);            return HttpClients.custom().setSSLSocketFactory(sslsf).build();        } catch (KeyManagementException e) {            e.printStackTrace();        } catch (NoSuchAlgorithmException e) {            e.printStackTrace();        } catch (KeyStoreException e) {            e.printStackTrace();        }        return  HttpClients.createDefault();    }}

二.post与get请求

/** * 利用HttpClient的工具类 *  * @author Joey * */public class HttpClientUtil {        private static String charSet = "UTF-8";    private static CloseableHttpClient httpClient = null;    private static CloseableHttpResponse response = null;        /**     * https的post请求     * @param url     * @param jsonstr     * @param charset     * @return     */    public static String doHttpsPost(String url, String jsonStr) {        try {            httpClient = SSLClient.createSSLClientDefault();            HttpPost httpPost = new HttpPost(url);            httpPost.setHeader("Content-Type", "application/json");                        StringEntity se = new StringEntity(jsonStr);            se.setContentType("text/json");            se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));            httpPost.setEntity(se);                        response = httpClient.execute(httpPost);            if (response != null) {                HttpEntity resEntity = response.getEntity();                if (resEntity != null) {                    return EntityUtils.toString(resEntity, charSet);                }            }        } catch (Exception ex) {            ex.printStackTrace();        }finally {             if(httpClient != null){                    try {                        httpClient.close();                    } catch (IOException e) {                        e.printStackTrace();                    }                }                if(response != null){                    try {                        response.close();                    } catch (IOException e) {                        e.printStackTrace();                    }                }        }        return null;    }        /**     * http的post请求(用于key-value格式的参数)      * @param url     * @param param     * @return     */    public static String doHttpPost(String url,Map
param){ try { //请求发起客户端 httpClient = HttpClients.createDefault(); //参数集合 List
postParams = new ArrayList
(); //遍历参数并添加到集合 for(Map.Entry
entry:param.entrySet()){ postParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } //通过post方式访问 HttpPost post = new HttpPost(url); HttpEntity paramEntity = new UrlEncodedFormEntity(postParams,charSet); post.setEntity(paramEntity); response = httpClient.execute(post); StatusLine status = response.getStatusLine(); int state = status.getStatusCode(); if (state == HttpStatus.SC_OK) { HttpEntity valueEntity = response.getEntity(); String content = EntityUtils.toString(valueEntity); //jsonObject = JSONObject.fromObject(content); return content; } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ if(httpClient != null){ try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } if(response != null){ try { response.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } /** * http的post请求(用于请求json格式的参数) * @param url * @param params * @return */ public static String doHttpPost(String url, String jsonStr) { try { httpClient = HttpClients.createDefault(); // 创建httpPost HttpPost httpPost = new HttpPost(url); httpPost.setHeader("Accept", "application/json"); StringEntity entity = new StringEntity(jsonStr, charSet); entity.setContentType("text/json"); entity.setContentEncoding(new BasicHeader("Content-Type", "application/json")); httpPost.setEntity(entity); //发送post请求 response = httpClient.execute(httpPost); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity responseEntity = response.getEntity(); String jsonString = EntityUtils.toString(responseEntity); return jsonString; } }catch(Exception e) { e.printStackTrace(); }finally { if(httpClient != null){ try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } if(response != null){ try { response.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } /** * http的Get请求 * @param url * @param param * @return */ public static String doHttpGet(String url,Map
param) { CloseableHttpClient httpclient = null; CloseableHttpResponse response = null; try { httpclient = HttpClients.createDefault(); if(param != null && !param.isEmpty()) { //参数集合 List
getParams = new ArrayList
(); for(Map.Entry
entry:param.entrySet()){ getParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } url +="?"+EntityUtils.toString(new UrlEncodedFormEntity(getParams), "UTF-8"); } //发送gey请求 HttpGet httpGet = new HttpGet(url); response = httpclient.execute(httpGet); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { return EntityUtils.toString(response.getEntity()); } }catch(Exception e) { e.printStackTrace(); }finally{ if(httpclient != null){ try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } if(response != null){ try { response.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } }
View Code

 

转载于:https://www.cnblogs.com/JoeyWong/p/9040868.html

你可能感兴趣的文章
SQL Server安全 2:身份验证
查看>>
算法集锦(二)
查看>>
ThinkPHP5 公共函数
查看>>
Java 基本数据类型
查看>>
LNMP 参数调优 ( 无注释 )
查看>>
pageoffice
查看>>
putty提供的两个文件传输工具PSCP、PSFTP详细介绍
查看>>
好的程序员有3种美德,
查看>>
BAT面试需要什么样的程序员?
查看>>
认识Java Core和Heap Dump
查看>>
NYOJ61 传纸条(一) 双线程dp
查看>>
数组拍平最优解
查看>>
leetcode 303. Range Sum Query - Immutable
查看>>
java中的生产者模式
查看>>
Rabin Karp 算法实战
查看>>
IIS7启用静态压缩
查看>>
Scala进阶之路-进程控制之执行shell脚本
查看>>
MySQL高可用架构之Mycat-关于Mycat安装和参数设置详解
查看>>
MapReduce编程模型及其在Hadoop上的实现
查看>>
SEH(__try,__except)
查看>>