httpClient发送https请求

前言

       我们知道现在的http请求应用的越来越广泛,最常见的场景就是浏览器作为http请求的客户端,请求http服务端。在浏览器发送请求时,会封装请求行,请求头,请求体信息,那我们在用java代码模拟时,也需要带上http请求的这些相关信息。java自带的java.net包是关于java的网络方面的包,但是没有完全的封装好的方法,而org.apache.httpcomponents下的httpclient包封装了完备的进行http请求的方法。本文也是基于这个包进行的论述

get请求模拟

        使用httpclient请求的步骤是:

1.创建默认的httpclient客户端

// 创建默认的httpclient客户端
CloseableHttpClient client = HttpClients.createDefault();

2.通过请求的url初始化一个HttpGet请求

// 通过请求的url初始化一个HttpGet请求
HttpGet get = new HttpGet("http://www.baidu.com");

3.通过客户端来执行请求

// 通过客户端来执行请求
CloseableHttpResponse response = client.execute(get);

4.处理返回的结果

// 获得响应行
System.out.println(response.getStatusLine().toString());
// 获得响应头		
Header[] headers = response.getAllHeaders();
for(Header header : headers ){
    System.out.println(header.getName() +" : "+header.getName());
}		
// 获得响应体
HttpEntity e = response.getEntity();
System.out.println(EntityUtils.toString(e,"UTF-8"));

post请求模拟

        post请求与get请求类似,只是在传递参数过程中稍有不同。

1.创建默认的httpClient客户端

// 创建默认的httpclient客户端
CloseableHttpClient client = HttpClients.createDefault();

2.通过请求的url初始化一个httpPost

// 通过请求的url初始化一个HttpGet请求
HttpPost httpPost = new HttpPost("http://localhoost/test");

3.参数设置

// 设置头部参数
httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
httpPost.addHeader("Accept", "application/json");
// 参数设置
JSONObject obj = new JSONObject();
obj.put("param1", "1");
obj.put("param2", "2");
// 解决中文乱码问题
StringEntity stringEntity = new StringEntity(obj.toString(), "UTF-8");
stringEntity.setContentEncoding("UTF-8");
httpPost.setEntity(stringEntity);

4.通过客户端来执行请求

CloseableHttpResponse response = client.execute(httpPost);

5.处理返回结果

System.out.println(response);

https请求

上面的post请求是基于http传输的,如果要基于https,首先需要创建keystore。可以利用jdk自带的keytool工具来生成


与上面的区别主要在于:

1.要通过keystore文件和密码来初始化SSLContext

// 初始化SSLContext
SSLContext sslcontext = custom("D:\\test.keystore","123456");
public static SSLContext custom(String keyStorePath, String keyStorepass){
        SSLContext sc = null;
        FileInputStream instream = null;
        KeyStore trustStore = null;
        try {
            trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            instream = new FileInputStream(new File(keyStorePath));
            trustStore.load(instream, keyStorepass.toCharArray());
            // 相信自己的CA和所有自签名的证书
            sc = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
        } catch (KeyStoreException | NoSuchAlgorithmException| CertificateException | IOException | KeyManagementException e) {
            e.printStackTrace();
        } finally {
            try {
                instream.close();
            } catch (IOException e) {
            }
        }
        return sc;
    }

2.设置协议http和https对应的处理socket链接工厂的对象

        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(sslcontext))
            .build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        HttpClients.custom().setConnectionManager(connManager);

3.创建自定义的httpclient对象

CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(connManager).build();
其他的都与上面的post请求保持一致
  • 11
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用httpclient发送https请求的步骤如下: 1. 创建HttpClient对象 首先,需要创建一个HttpClient对象。可以使用DefaultHttpClient类或HttpClientBuilder类来创建。 2. 创建HttpsURLConnection对象 使用URL对象的openConnection()方法创建HttpsURLConnection对象。 3. 设置SSLContext和TrustManager 为了支持https请求,需要设置SSLContext和TrustManager。SSLContext可以使用SSLContext.getInstance("TLS")来获取,TrustManager可以使用X509TrustManager实现。 4. 设置HostnameVerifier 设置HostnameVerifier,验证请求的主机名是否和证书中的主机名一致。可以使用DefaultHostnameVerifier类或自定义的HostnameVerifier类。 5. 设置请求头 可以使用setRequestProperty()方法设置请求头,比如User-Agent、Accept、Content-Type等。 6. 发送请求并获取响应 使用HttpURLConnection的getInputStream()方法获取响应的输入流,并使用IO流的方式读取响应数据。 示例代码如下: ```java // 创建HttpClient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建HttpGet对象 HttpGet httpGet = new HttpGet("https://www.example.com"); // 发送请求并获取响应 CloseableHttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); // 读取响应数据 String result = EntityUtils.toString(entity, "UTF-8"); // 关闭响应和HttpClient对象 response.close(); httpClient.close(); ``` 需要注意的是,为了保证安全性,https请求中的证书需要进行验证。可以使用TrustManager来验证服务器证书的合法性,也可以使用自定义的SSLSocketFactory来忽略证书验证。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值