封装HttpClient进行http请求与https请求

一.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<String,String> param){
        try {
            //请求发起客户端
            httpClient = HttpClients.createDefault();
            //参数集合
            List<NameValuePair> postParams = new ArrayList<NameValuePair>();
            //遍历参数并添加到集合
            for(Map.Entry<String, String> 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<String,String> param) {
        CloseableHttpClient httpclient = null;
        CloseableHttpResponse response = null;

        try {
            httpclient = HttpClients.createDefault();
            if(param != null && !param.isEmpty()) {
                //参数集合
                List<NameValuePair> getParams = new ArrayList<NameValuePair>();
                for(Map.Entry<String, String> 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;
    }

}

原文地址:https://www.cnblogs.com/JoeyWong/p/9040868.html

时间: 2024-08-28 01:44:25

封装HttpClient进行http请求与https请求的相关文章

httpclient 3.1跳过https请求SSL的验证

一.因为在使用https发送请求的时候会涉及,验证方式.但是这种方式在使用的时候很不方便.特别是在请求外部接口的时候,所以这我写了一个跳过验证的方式.(供参考) 二.加入包,这里用的是commons-httpclient 3.1 的包.一般请求采用最新的httpclient4.5就可以了 <dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</

httpclient绕过证书验证进行HTTPS请求

http请求是我们常用的一种web应用的应用层协议,但是由于它的不安全性,现在正在逐渐向https协议过渡.https协议是在http的基础上进行了隧道加密,加密方式有SSL和TLS两种.当server用https协议进行数据交换后,client请求server时会对server的证书进行校验,如果server端证书为四大证书机构颁发的证书或者其授权机构颁发的证书,则允许进一步请求,否则会警告证书不受信任.更多信息可参考https://www.cnblogs.com/handsomeBoys/p

支持https请求以及https请求的抓包

iOS9推出的时候,苹果希望大家使用https协议,来提高数据传输之间的安全性.下面我就从最简单的代码介绍,如何在工程中设置,来支持https的请求. 一.证书准备篇 1.证书转换 在服务器人员,给你发送的crt证书后,进到证书路径,执行下面语句 // openssl x509 -in 你的证书.crt -out 你的证书.cer -outform der 这样你就可以得到cer类型的证书了.双击,导入电脑. 2.证书放入工程 1.可以直接把转换好的cer文件拖动到工程中. 2.可以在钥匙串内,

android json实现网络请求 和普通的http请求 还有https请求安全认证

android 实现http请求很多种,和服务器对接需要了解 在 Android 下,Android SDK 已经为我们封装好了整个与 JSON 有关的操作,使用非常方便 直接上代码 /** * 发送 http 请求 * * @param url */ @SuppressLint("DefaultLocale") public int httpResponseCodeJsonPost(String strUrl, String authorization, String current

[PHP自动化-进阶]003.CURL处理Https请求访问

引言:继前文<模拟登录并采集数据>,<模拟登录带有验证码的网站>,大家对CURL基本上已经有了认识,这一讲简单的说一下请求Https. 在很多的站点,如TalkingData, BaiDu等等,一些请求协议都是走SSL,大白话来说就是Https,这种协议在模拟CURL时可能会出现请求不成功等等的问题. 下面为大家讲一下解决方案. 这一讲很简单,但能说明问题……. 异常提示 大多数异常信息提示如下:证书验证失败. SSL certificate problem, verify tha

AFNetWorking3.0使用 自签名证书的https请求

前几日,项目组出于安全角度的考虑,要求项目中的请求使用https请求,因为是企业内部使用的app,因此使用了自签名的证书,而自签名的证书是不受信任的,所以我们就需要自己来做证书的验证,包括服务器验证客户端的证书和我们要信任服务器的证书,SSL双向认证的原理我这里就不赘述了,这里提供两篇博客 iOS安全系列之一:HTTPS: http://oncenote.com/2014/10/21/Security-1-HTTPS/ iOS安全系列之二:HTTPS进阶: http://oncenote.com

Volley框架支持HTTPS请求。

第一次写帖子,嘿嘿. 最近了解到google2013IO大会出了个网络框架,正好项目也需要用到,就看了下. 最后发现接口都是HTTPS的,但是Volley默认是不支持HTTPS,网上找了好久,都没有对Volley HTTPS请求做解答. 所以分享下心得. bvin大神已经分析框架的帖子 在下面的传送: 谷歌Volley网络框架讲解——第一篇 谷歌Volley网络框架讲解——Network及其实现类 谷歌Volley网络框架讲解——网络枢纽 谷歌Volley网络框架讲解——HttpStack及其实

SPRING IN ACTION 第4版笔记-第九章Securing web applications-011-把敏感信息请求转为https(requiresChannel())

1.把包含敏感信息的请求转为https请求,则较为安全,但如何只把有需要安全的请求转为https,而不是不加分辩就把所有请求都转为https呢?可以用requiresChannel() 1 @Override 2 protected void configure(HttpSecurity http) throws Exception { 3 http 4 .authorizeRequests() 5 .antMatchers("/spitter/me").hasRole("S

HttpClient 发送 HTTP、HTTPS 请求的简单封装

序 最近这几周,一直在忙同一个项目,刚开始是了解需求,需求有一定了解之后,就开始调第三方的接口.由于第三方给提供的文档很模糊,在调接口的时候,出了很多问题,一直在沟通协调,具体的无奈就不说了,由于接口的访问协议是通过 HTTP 和 HTTPS 通讯的,因此封装了一个简单的请求工具类,由于时间紧迫,并没有额外的时间对工具类进行优化和扩展,如果后续空出时间的话,我会对该工具类继续进行优化和扩展的. 引用 首先说一下该类中需要引入的 jar 包,apache 的 httpclient 包,版本号为 4