HttpClient4.3.6 实现https访问

package httptest;

import java.io.IOException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * @author yan
 * @date 2016-6-9 11:03:04
 * @version V1.0
 * @desc
 */
public class HttpsUtil {

    public static final String get(final String url, final Map<String, Object> params) {
        StringBuilder sb = new StringBuilder("");

        if (null != params && !params.isEmpty()) {
            int i = 0;
            for (String key : params.keySet()) {
                if (i == 0) {
                    sb.append("?");
                } else {
                    sb.append("&");
                }
                sb.append(key).append("=").append(params.get(key));
                i++;
            }
        }

        CloseableHttpClient httpClient = createSSLClientDefault();

        CloseableHttpResponse response = null;
        HttpGet get = new HttpGet(url + sb.toString());
        String result = "";

        try {
            response = httpClient.execute(get);

            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                if (null != entity) {
                    result = EntityUtils.toString(entity, "UTF-8");
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(HttpsUtil.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (null != response) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException ex) {
                    Logger.getLogger(HttpsUtil.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

        return result;
    }

    public static final String post(final String url, final Map<String, Object> params) {
        CloseableHttpClient httpClient = createSSLClientDefault();
        HttpPost post = new HttpPost(url);

        CloseableHttpResponse response = null;

        if (null != params && !params.isEmpty()) {
            List<NameValuePair> nvpList = new ArrayList<NameValuePair>();
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                NameValuePair nvp = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
                nvpList.add(nvp);
            }
            post.setEntity(new UrlEncodedFormEntity(nvpList, Charset.forName("UTF-8")));
        }

        String result = "";

        try {
            response = httpClient.execute(post);

            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                if (null != entity) {
                    result = EntityUtils.toString(entity, "UTF-8");
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(HttpsUtil.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (null != response) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException ex) {
                    Logger.getLogger(HttpsUtil.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

        return result;
    }

    private static CloseableHttpClient createSSLClientDefault() {

        SSLContext sslContext;
        try {
            sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                //信任所有
                @Override
                public boolean isTrusted(X509Certificate[] xcs, String string){
                    return true;
                }
            }).build();

            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);

            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyStoreException ex) {
            Logger.getLogger(HttpsUtil.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(HttpsUtil.class.getName()).log(Level.SEVERE, null, ex);
        } catch (KeyManagementException ex) {
            Logger.getLogger(HttpsUtil.class.getName()).log(Level.SEVERE, null, ex);
        }

        return HttpClients.createDefault();
    }

    public static void main(String[] args) {
        System.out.println("Result:" + get("https://github.com/", null));
    }
}
时间: 2024-10-11 14:51:08

HttpClient4.3.6 实现https访问的相关文章

Tomcat创建HTTPS访问,java访问https

一 https和ssL HTTPS(全称:Hyper Text Transfer Protocol over Secure Socket Layer),是以安全为目标的HTTP通道,简单讲是HTTP的安全版.即HTTP下加入SSL层,HTTPS的安全基础是SSL,因此加密的详细内容就需要SSL. 它是一个URI scheme(抽象标识符体系),句法类同http:体系.用于安全的HTTP数据传输.https:URL表明它使用了HTTP,但HTTPS存在不同于HTTP的默认端口及一个加密/身份验证层

Apache配置SSL 实现https访问

本次坏境:CA和apache为同一台主机 先使本机作为CA服务端: [[email protected]~]#yum -y install openssl openssl-devel [[email protected]~]#vi /etc/pki/tls/openssl.cnf [ CA_default ] dir = ../../CA 改为: [ CA_default ] dir= /etc/pki/CA 为了减少不必要的重复操作,可以预先定义[ req_distinguished_name

centos7安装tengine强制使用HTTPS访问

操作系统:centos7.2 x64tengine:Tengine/2.2.0主机IP: 10.0.0.12 一.安装tengine 1.1 下载源码安装包 1.1.1 源码包pcre-8.40            用于支持正则表达式 [[email protected] ~]# cd /usr/local/src/ [[email protected] src]# wget ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-

新手玩阿里云ECS搭建CentOS5.8搭建svn服务器支持https访问方式

关于svn,之前我也不了解这是个什么东西,去年(大二)的时候,在学校接触过一个项目,当时就用到了这个,也都不是我配置的,都是别人给我整好了,我就写代码呗,写了就提交上去,当时也没有考虑过什么事svn,现在在公司实习了,时间很充裕,就想玩玩svn,也顺便把我准备做的毕业设计都传上去,阿里云给了我机会,新手注册,ECS免费半年,多好的事,虽然没有外网带宽,但是买1M的外网带宽也就20多块钱一个月吧!我还是可以接受的,好了不废话了,阿里云在这里就不废话了,反正感觉很高大上,在这里就简单聊聊svn吧!也

Windows下Nginx配置SSL实现Https访问(包含证书生成)

Vincent.李 Windows下Nginx配置SSL实现Https访问(包含证书生成) Windows下Nginx配置SSL实现Https访问(包含证书生成) 首先要说明为什么要实现https? HTTP全名超文本传输协议,客户端据此获取服务器上的超文本内容.超文本内容则以HTML为主,客户端拿到HTML内容后可根据规范进行解析呈现.因此,HTTP主要负责的是"内容的请求和获取".问题就出在这部分.行监控.劫持.阻挡等行为很容易导致网站泄密,一些关键参数比如登录密码开发者会在客户端

web服务之Apache实现的https访问

本文旨在实践httpd-2.4基于域名的虚拟主机配置,让指定用户访问站点状态信息,并为站点提供https服务. 知识储备 HTTPS协议 HTTPS协议就是"HTTP协议"和"SSL/TLS"协议的结合,HTTP over SSL"或"HTTP over TLS",对http协议的文本数据进行加密处理后,成为二进制形式传输. SSL会话简化过程 (1) 客户端发送可供选择的加密方式,并向服务器请求证书: (2) 服务器端发送证书以及选定

Apache环境修改.htaccess文件实现子目录强制HTTPS访问

如果要在Apache环境下实现子目录强制HTTPS地址访问,该怎么实现呢?在此文章中将与大家一起分享如何在Apache环境下修改.htaccess文件来实现子目录强制HTTPS地址访问. 1.根目录域名.甚至比较简单,在.htaccess文件中增加下面代码即可,请记得改成自己域名. RewriteEngine On RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://www.网站域名.com/$1 [R,L] 2.子目录实现强制跳转h

Nginx负载均衡实现https访问

整体流程:1.搭建tomcat项目集群(默认完成) 2.安装nginx需要的库 3.安装Nginx并修改配置文件 4.启动测试 1.1.1. 安装Nginx 1.1.1.1. 安装环境: 安装pcre库 yum -y install pcre-devel 安装zlib库 yum install -y zlib-devel 安装openssl库 yum install -y openssl openssl-devel   或者  编译安装 编译安装openssl: 1.上传openssl压缩包 按

CentOS7安装lamp并实现Xcache、https访问

            LAMP指的是Linux(操作系统).ApacheHTTP 服务器,MySQL数据库(有时也指MariaDB) 和Php(有时也是指perl或python) ,他们共同组成了一个强大的Web应用程序平台. https全称为Hyper Text Transfer Protocol over Secure Socket Layer:基于http支持ssl协议,主要作用是用于安全的传输数据:http是超文本的传输协议,信息是明文的,安全性很低:而https则是具有安全性的ssl