最核心的應該也就這段了,備份留念。
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();
}
}
}