【JAVA實戰案例】HttpClientTest

本文介绍了一种使用Java实现HTTPS Post请求的方法。该方法通过Apache HttpClient库完成,并演示了如何加载自定义证书、配置SSL连接及执行基本认证的过程。此外,还提供了完整的代码示例,包括异常处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最核心的應該也就這段了,備份留念。

package com.httpclient.model;

import com.alibaba.fastjson.JSONObject;
import com.httpclient.model.vo.CcmDataVo;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.ParseException;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.List;

public class HttpClientTest {

    private static final String CERT = "D:\\cacerts\\mycert.pfx";
    private static final String CERT_PASSWORD = "password";
    private static final String USER_NAME = "username";
    private static final String PASSWORD = "password";
    private static final String URL = "url";

    /**
     * 加载证书
     * @param password
     * @return
     * @throws Exception
     */
    private static KeyStore getKeyStore(String password) throws Exception {
        KeyStore ks = KeyStore.getInstance("PKCS12");
        FileInputStream fis = new FileInputStream(CERT);
        ks.load(fis, password.toCharArray());
        fis.close();
        return ks;
    }

    private static SSLContext getSSLContext() throws Exception {
        SSLContext sslContext = SSLContexts.custom()
                .loadKeyMaterial(getKeyStore(CERT_PASSWORD),CERT_PASSWORD.toCharArray())
                .build();
        return sslContext;
    }

    /**
     * 获取CloseableHttpClient
     *
     * @return
     * @throws Exception
     */
    public static CloseableHttpClient getHttpClient() throws Exception {
        SSLContext ssl = getSSLContext();
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(new SSLConnectionSocketFactory(ssl)).build();
        return httpClient;
    }

    /**
     * 设置用户名和密码
     * @param target  httppost对象
     * @param username 用户名
     * @param password 密码
     * @return HttpClientContext
     */
    private static HttpClientContext getHttpClientContext(HttpHost target, String username, String password) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
                new UsernamePasswordCredentials(username, password));
        HttpClientContext localContext = HttpClientContext.create();
        BasicScheme basicAuth = new BasicScheme();
        AuthCache authCache = new BasicAuthCache();
        authCache.put(target, basicAuth);
        localContext.setAuthCache(authCache);
        localContext.setCredentialsProvider(credsProvider);
        return localContext;
    }

    /**
     * post请求demo
     */
    public static void doPostTest() throws Exception {
        // 创建Http客户端
        CloseableHttpClient httpClient = getHttpClient();
        URI uri = new URI(URL);
        HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
        // 创建Post请求
        HttpPost httpPost = new HttpPost(uri);
        // 将Object转换为json字符串
        String jsonString = getBody();
        StringEntity entity = new StringEntity(jsonString, "UTF-8");
        entity.setContentType("application/json");
        entity.setContentEncoding("UTF-8");
        // 将entity放入post请求体中
        httpPost.setEntity(entity);
        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // http basic鉴权设置(在这里设置用户名、密码)
            HttpClientContext clientContext = getHttpClientContext(target, USER_NAME, PASSWORD);
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(target, httpPost, clientContext);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            System.out.println();
            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                String content = EntityUtils.toString(responseEntity);
                System.out.println("响应内容为:" + content);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static String getBody() {
        CcmDataVo vo = new CcmDataVo("...");//測試數據,另有Class
        List<CcmDataVo> list = new ArrayList<>();
        list.add(vo);
        return JSONObject.toJSONString(list);
    }

    public static void main(String[] args) {
        try {
            HttpClientTest.doPostTest();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值