主要问题在于如何跳过证明书。
父类:HTTPSClient
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
public abstract class HTTPSClient extends HttpClientBuilder {
private CloseableHttpClient client;
protected ConnectionSocketFactory connectionSocketFactory;
public CloseableHttpClient init() throws Exception {
this.prepareCertificate();
this.regist();
return this.client;
}
public abstract void prepareCertificate() throws Exception;
protected void regist() {
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", this.connectionSocketFactory)
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
HttpClients.custom().setConnectionManager(connManager);
this.client = HttpClients.custom().setConnectionManager(connManager).build();
}
}
加载证明书的话:HTTPSCertifiedClient
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;
import javax.net.ssl.SSLContext;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.ssl.SSLContexts;
public class HTTPSCertifiedClient extends HTTPSClient {
public HTTPSCertifiedClient() {
}
@Override
public void prepareCertificate() throws Exception {
// KeyStoreを取得します
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream instream = new FileInputStream(
new File("C:/xxxx/xxx.keystore"));
try {
trustStore.load(instream, "password".toCharArray());
} finally {
instream.close();
}
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, TrustSelfSignedStrategy.INSTANCE)
.build();
this.connectionSocketFactory = new SSLConnectionSocketFactory(sslcontext);
}
}
跳过证明书的话
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.ssl.SSLContexts;
public class HTTPSTrustClient extends HTTPSClient {
public HTTPSTrustClient() {
}
@Override
public void prepareCertificate() throws Exception {
this.connectionSocketFactory = new SSLConnectionSocketFactory(
SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),NoopHostnameVerifier.INSTANCE
);
}
}
封装Get,Post方法:HTTPSClientUtil
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class HTTPSClientUtil {
private static final String DEFAULT_CHARSET = "UTF-8";
public static String doPost(HttpClient httpClient, String url, Map<String, String> paramHeader,
Map<String, String> paramBody) throws Exception {
return doPost(httpClient, url, paramHeader, paramBody, DEFAULT_CHARSET);
}
public static String doPost(HttpClient httpClient, String url, Map<String, String> paramHeader,
Map<String, String> paramBody, String charset) throws Exception {
String result = null;
HttpPost httpPost = new HttpPost(url);
setHeader(httpPost, paramHeader);
setBody(httpPost, paramBody, charset);
HttpResponse response = httpClient.execute(httpPost);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, charset);
}
}
return result;
}
public static String doPost(HttpClient httpClient, String url, Map<String, String> paramHeader,
String paramBody) throws Exception {
return doPost(httpClient, url, paramHeader, paramBody, DEFAULT_CHARSET);
}
public static String doPost(HttpClient httpClient, String url, Map<String, String> paramHeader,
String paramBody, String charset) throws Exception {
String result = null;
HttpPost httpPost = new HttpPost(url);
setHeader(httpPost, paramHeader);
httpPost.setEntity(new StringEntity(paramBody, charset));
HttpResponse response = httpClient.execute(httpPost);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, charset);
}
}
return result;
}
public static String doGet(HttpClient httpClient, String url, Map<String, String> paramHeader,
Map<String, String> paramBody) throws Exception {
return doGet(httpClient, url, paramHeader, paramBody, DEFAULT_CHARSET);
}
public static String doGet(HttpClient httpClient, String url, Map<String, String> paramHeader,
Map<String, String> paramBody, String charset) throws Exception {
String result = null;
HttpGet httpGet = new HttpGet(url);
setHeader(httpGet, paramHeader);
HttpResponse response = httpClient.execute(httpGet);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, charset);
}
}
return result;
}
private static void setHeader(HttpRequestBase request, Map<String, String> paramHeader) {
if (paramHeader != null) {
Set<String> keySet = paramHeader.keySet();
for (String key : keySet) {
request.addHeader(key, paramHeader.get(key));
}
}
}
private static void setBody(HttpPost httpPost, Map<String, String> paramBody, String charset) throws Exception {
if (paramBody != null) {
List<NameValuePair> list = new ArrayList<NameValuePair>();
Set<String> keySet = paramBody.keySet();
for (String key : keySet) {
list.add(new BasicNameValuePair(key, paramBody.get(key)));
}
if (list.size() > 0) {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
httpPost.setEntity(entity);
}
}
}
}
工具类:JSONUtils
import com.fasterxml.jackson.databind.ObjectMapper;
public class JSONUtils {
private JSONUtils() {}
public static String getPrettyJson(String jsonData) {
try {
ObjectMapper mapper = new ObjectMapper();
Object jsonObject = mapper.readValue(jsonData, Object.class);
String prettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
return prettyJson;
} catch (Exception e) {
System.out.println("Can't convert input string to pretty json.");
return jsonData;
}
}
}
工具类:PropertiesUtils
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
public class PropertiesUtils {
public static Properties readProperties(String propertiesPath) throws IOException {
InputStream inputStream = new FileInputStream(propertiesPath);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
Properties properties = new Properties();
properties.load(bufferedReader);
return properties;
}
}
工具类:StringUtils
public class StringUtils {
private StringUtils() {}
public static boolean isBlank(String str) {
return str == null || str.isBlank();
}
}
工具类:TxtUtils
通过resolveCharset()方法来判断文件编码,
但是前提是文件必须有BOM头。
没有BOM头时默认为是UTF-8,实际可能是任意的编码文件。
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class TxtUtils {
private TxtUtils() {
}
public static final String DEFAULT_CHARSET = "\t";
public static final String SHIFT_JIS = "SHIFT_JIS";
public static final String UTF_8 = "UTF-8";
public static final String UTF_16 = "UTF-16";
public static final String UNICODE = "Unicode";
public static final String HTTP = "http";
public static final String DEFAULT_ENCODE = UTF_8;
public static List<String> readDupLines(String filePath) throws IOException {
List<String> ret = new ArrayList<String>();
List<String> lines = new ArrayList<String>();
if (StringUtils.isBlank(filePath)) {
return null;
}
InputStream inputStream = getInputStream(filePath);
if (inputStream == null) {
return null;
}
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, resolveCharset(filePath));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String text;
while ((text = bufferedReader.readLine()) != null) {
if (lines.contains(text)) {
ret.add(text);
}
lines.add(text);
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
return ret;
}
public static List<String> readNoDupLines(String filePath) throws IOException {
List<String> lines = new ArrayList<String>();
if (StringUtils.isBlank(filePath)) {
return null;
}
InputStream inputStream = getInputStream(filePath);
if (inputStream == null) {
return null;
}
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, resolveCharset(filePath));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String text;
while ((text = bufferedReader.readLine()) != null) {
if (!lines.contains(text)) {
lines.add(text);
}
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
return lines;
}
public static StringBuilder readTxtFile(String filePath) throws IOException {
if (StringUtils.isBlank(filePath)) {
return null;
}
StringBuilder sb = new StringBuilder();
InputStream inputStream = getInputStream(filePath);
if (inputStream == null) {
return sb;
}
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, resolveCharset(filePath));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String text;
while ((text = bufferedReader.readLine()) != null) {
sb.append(text).append(System.lineSeparator());
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
return sb;
}
public static String readTxtFileNoSepLine(String filePath) throws IOException {
if (StringUtils.isBlank(filePath)) {
return null;
}
StringBuilder sb = new StringBuilder();
InputStream inputStream = getInputStream(filePath);
if (inputStream == null) {
return null;
}
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, resolveCharset(filePath));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String text;
while ((text = bufferedReader.readLine()) != null) {
sb.append(text);
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
return sb.toString();
}
public static String readTxtFileString(String filePath) {
String content = null;
try (Reader reader = new InputStreamReader(new FileInputStream(filePath), resolveCharset(filePath))) {
StringBuilder sb = new StringBuilder();
char[] tempchars = new char[1024];
while (reader.read(tempchars) != -1) {
sb.append(tempchars);
}
content = sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
public static String resolveCharset(String filePath) {
return resolveCharset(getInputStream(filePath));
}
public static String resolveCharset(InputStream inputStream) {
if (inputStream == null) {
return SHIFT_JIS;
}
byte[] head = new byte[3];
try {
inputStream.read(head);
} catch (IOException e) {
e.printStackTrace();
}
if (head[0] == -1 && head[1] == -2 ) {
return UTF_16;
} else if (head[0] == -2 && head[1] == -1 ) {
return UNICODE;
} else if(head[0] == -17 && head[1] == -69 && head[2] == -65) {
return UTF_8;
}
return DEFAULT_ENCODE;
}
public static InputStream getInputStream(String filePath) {
if (StringUtils.isBlank(filePath)) {
return null;
}
if (filePath.contains(HTTP)) {
try {
return new URL(filePath).openStream();
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
return new FileInputStream(filePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
return null;
}
public static void writeFile(String path, String content){
File file = new File(path);
try {
if(!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
file.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(path, false);
fileWriter.write(content);
}catch (IOException e){
e.printStackTrace();
}finally {
try {
fileWriter.flush();
fileWriter.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}
Main Class:Application
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.apache.http.client.HttpClient;
public class Application {
private static final String CONFIG_FULL_PATH = "./config/config.properties";
private static final String REQUEST_PATH = "./request/";
private static final String RESPONSE_PATH = "./response/";
private static final String KEY_REQUEST_ID = "REQUEST_ID";
private static final String KEY_OPENAPI_URL = "OpenApiUrl";
public static void main(String[] args) throws Exception {
String requestId = System.getProperty(KEY_REQUEST_ID);
if (StringUtils.isBlank(requestId)) {
System.out.println("Pls input -DREQUEST_ID");
System.exit(9);
}
String requestFile = REQUEST_PATH + requestId + ".json";
String reponseFile = RESPONSE_PATH + requestId + "_output.json";
Properties configProp = PropertiesUtils.readProperties(CONFIG_FULL_PATH);
String url = configProp.getProperty(KEY_OPENAPI_URL);
String requestData = TxtUtils.readTxtFileNoSepLine(requestFile).toString();
if (StringUtils.isBlank(requestData)) {
System.out.println("Can't read request file:" + requestFile);
System.exit(9);
}
HttpClient httpClient = new HTTPSTrustClient().init();
Map<String, String> paramHeader = new HashMap<>();
paramHeader.put("Content-Type", "application/json");
// paramHeader.put("Authorization", "XXXX");
paramHeader.put("Accept", "application/json");
String result = HTTPSClientUtil.doPost(httpClient, url, paramHeader, requestData);
String prettyJson = JSONUtils.getPrettyJson(result);
System.out.println(prettyJson);
TxtUtils.writeFile(reponseFile, prettyJson);
}
}
POM
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>lanzy.https.client</groupId>
<artifactId>apistub</artifactId>
<version>1.0.0</version>
<name>apistub</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.14</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>lanzy.https.client.apistub.Application</mainClass>
</manifest>
</archive>
<finalName>apistub</finalName>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-lib</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
<overWriteReleases>false</overWriteReleases>
<overWriteSnapshots>false</overWriteSnapshots>
<overWriteIfNewer>true</overWriteIfNewer>
<includeScope>compile</includeScope>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
config.properties
文件编码:UTF-8 BOM
OpenApiUrl=https://xxx/api/v1/xxx
request:test_0000.json
[{
"xxx": {
"xxx": {
"xxx": "xxx",
"xxx": "xxx"
}
},
"XXX": "xxxxxxxxxxxx"
}]
reponse:准备reponse目录
网友评论