通过 Apache Commons HttpClient 发送 HTTPS 请求

1、通过 HTTPS 发送 POST 请求;

2、HTTPS 安全协议采用 TLSv1.2;

3、 使用代理(Proxy)进行 HTTPS 访问;

4、指定 Content-Type 为:application/x-www-form-urlencoded;

5、HTTPS  请求时加载客户端证书(Client Certificate);

6、忽略服务器端证书链(Server Certificate Chain)的校验(Validate)。

public static void main(String[] args) throws IOException, UnrecoverableKeyException, CertificateException, KeyStoreException, KeyManagementException {
        SSLConnectionSocketFactory socketFactory = getSocketFactory();

        // 创建 CloseableHttpClient 对象
        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();

        // 指定请求的 URL 并创建 HttpPost 对象
        HttpPost httppost = new HttpPost("https://xxxx/yyyy");

        // 设置请求通过的代理
        httppost.setConfig(RequestConfig.custom().setProxy(new HttpHost("host", 8080)).build());
        HttpEntity entity;

        // 设置请求的 ContentType 为 application/x-www-form-urlencoded
        httppost.addHeader(HttpHeaders.CONTENT_TYPE, Consts.HTTP_REQUEST_CONTENTTYPE_FORM);

        // 构建 POST 的内容
        List<BasicNameValuePair> nvps = new ArrayList<>();
        nvps.add(new BasicNameValuePair("amount", "1.00"));
        entity = new UrlEncodedFormEntity(nvps, Consts.CHARSET_UTF8);
        httppost.setEntity(entity);
        CloseableHttpResponse response = null;
        try {
            // 发送请求
            response = httpclient.execute(httppost);

            // 获取响应内容
            HttpEntity entity1 = response.getEntity();
            System.out.println(EntityUtils.toString(entity1));
        } finally {
            if (null != response) {
                response.close();
            }
            if (null != httpclient) {
                httpclient.close();
            }
        }
    }

    // 忽略服务器端证书链的认证
    private static TrustManager getTrustManagers() {
        return new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        };
    }

    private static SSLConnectionSocketFactory getSocketFactory() throws IOException, KeyStoreException, CertificateException, UnrecoverableKeyException, KeyManagementException {
        SSLContext sslContext;
        try {
            // keyStore 用来存放客户端证书
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            FileInputStream instream = new FileInputStream(new File("d:\\test.p12"));
            try {
                keyStore.load(instream, "passwd".toCharArray());
            } finally {
                instream.close();
            }

            // 加载客户端证书,并设置HTTPS的安全协议为 TLSv1.2
            sslContext = SSLContexts.custom().loadKeyMaterial(keyStore, "passwd".toCharArray()).useProtocol("TLSv1.2").build();
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
        try {
            sslContext.init(null, new TrustManager[]{getTrustManagers()}, new java.security.SecureRandom());
        } catch (KeyManagementException e) {
            return null;
        }
        return new SSLConnectionSocketFactory(sslContext);
    }
时间: 2024-10-05 04:58:08

通过 Apache Commons HttpClient 发送 HTTPS 请求的相关文章

使用HttpClient发送HTTPS请求以及配置Tomcat支持SSL

这里使用的是HttpComponents-Client-4.1.2 1 package com.jadyer.util; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.FileNotFoundException; 6 import java.io.IOException; 7 import java.security.KeyManagementException; 8 import java

HTTPClient 发送HTTPS请求

HTTPClient 发送HTTP请求就不多说了, 现在给出发送HTTPS请求, 主要思路是忽略证书验证. /** * * @param url * @param contextType "image/jpeg","application/Json" * @return */ public static byte[] sendHttpsGetUrl(HttpClient httpClient1 ,String url,String contextType) { //

httpClient发送https 请求

做项目要用到httpClient发送https到服务器,要求URL中带参数,并且发送xml格式的报文,第一次做,在这里记录一下,以便以后查询的帮助别人:本文在证书配置正确的前提下执行 客户端代码;     public static void httpsRequest() throws Exception {      System.out.println("this is https");         KeyStore trustStore  = KeyStore.getInst

android使用apache httpclient发送post请求

package com.liuc; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.ht

httpClient使用中报错org.apache.commons.httpclient.HttpMethodBase - Going to buffer response body of large or unknown size.

在使用HttpClient发送请求,使用httpMethod.getResponseBodyAsString();时当返回值过大时会报错: org.apache.commons.httpclient.HttpMethodBase - Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended. 可以如下解决: 1 BufferedReade

java httpclient发送json 请求 ,go服务端接收

/***java客户端发送http请求*/package com.xx.httptest; /** * Created by yq on 16/6/27. */ import java.io.IOException; import java.net.URLEncoder; import org.apache.commons.httpclient.*; import org.apache.commons.httpclient.methods.GetMethod; import org.apache

Android系列之网络(三)----使用HttpClient发送HTTP请求(分别通过GET和POST方法发送数据)

[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4006009.html 联系方式:[email protected] [系列]Android系列之网络:(持续更新) Android系列之网络(一)----使用HttpClient发送HTTP请求(通过get方法获取数据) Android系列之网络(二)----HTTP请求头与响应头 Android

使用httpclient发送http请求

先来个httpclient的maven依赖 <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3</version> </dependency> SimpleHttpClient.java package com.openapi.TestPojo; im

Java编程之通过HttpClient发送HTTP请求

HttpClient时著名的开源软件组织Apache基金会下的一个子项目,它对HTTP协议通信的过程进行了封装,提供高效且功能丰富的客户端编程工具包. package cn.com.cis.claim.car.interf.common.service.facade; public interface HttpClientService { /** * HttpServlet+XML交互发送报文 * chengjie 2017-12-14 * @param strURL * @param req