背景描述
项目生产环境中有一个需求,原本通过httpClient Post + 域名的方式发起请求,该域名在服务器host上配置。现在要求生产环境也能向测试环境发起请求,并且域名不变,需要发起请求的用户指定IP。由于测试环境有多套,IP也不固定,结合这个需求我们决定采用HtppClient设置DNS的方式来实现。实现过程中,在网上查阅了很多资料,HttpClient设置DNS的方式有两种:
- 通过反射技术调用InetAddress类中的put方法设置DNS;
- 实现DnsResolver接口的resolve方法,结合HttpClient中的HttpClientConnectionManager完成DNS设置。
方式一代码实现:
- 工具类代码实现
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* @Author: Scallion
* @Date: 2021/12/3 4:14 下午
* @Version 1.0
*/
public class CustomDns {
public static void writeSystemDnsCache(String hostName, String ip) {
try {
Class inetAddressClass = InetAddress.class;
Field field = inetAddressClass.getDeclaredField("addressCache");
field.setAccessible(true);
Object object = field.get(inetAddressClass);
Class cacheClass = object.getClass();
System.out.println("addressCache: "+object);
Method putMethod = cacheClass.getDeclaredMethod("put", String.class, InetAddress[].class);
putMethod.setAccessible(true);
String[] ipStr = ip.split("\\.");
byte[] ipBuf = new byte[4];
for(int i = 0; i < 4; i++) {
ipBuf[i] = (byte) (Integer.parseInt(ipStr[i]) & 0xff);
}
putMethod.invoke(object, hostName, new InetAddress[] {InetAddress.getByAddress(ipBuf)});
System.out.println("addressCache: "+object);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
- 使用方式
在调用HttpClient Post 前,使用CustomDns类的writeSystemDnsCache方法进行设置DNS
public static void main(String[] args) {
CustomDns.writeSystemDnsCache("www.baidu.com","127.0.0.1");
//TODO HttpClient Post 调用
}
方式二实现:
- 自定义MyDnsResolver类,实现DnsResolver接口
import lombok.Data;
import org.apache.http.conn.DnsResolver;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
/**
* 自定义的 DNS 解析类
* @Author: Scallion
* @Date: 2021/12/6 5:45 下午
* @Version 1.0
*/
@Data
public class MyDnsResolver implements DnsResolver {
private Map<String, InetAddress[]> MAPPINGS;
public MyDnsResolver(Map<String, InetAddress[]> mappings) {
this.MAPPINGS = mappings;
}
public void addResolve(String host, String ip) {
try {
MAPPINGS.put(host, new InetAddress[]{InetAddress.getByName(ip)});
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
@Override
public InetAddress[] resolve(String host) throws UnknownHostException {
return MAPPINGS.containsKey(host) ? MAPPINGS.get(host) : new InetAddress[0];
}
}
- SslHttpUtil工具类实现
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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.config.RequestConfig;
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.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
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.BasicHttpClientConnectionManager;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.net.URI;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
public class SslHttpUtil {
private static String charSet = "UTF-8";
private static final String HOST = "www.baidu.com";
private static final Object lock = new Object();
/***
* 发起Post请求
* @param url
* @param params
* @return
* @throws Exception
*/
public static HttpResponse sendPost(String url, Map<String, String> params, String ip) throws Exception {
ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> param : params.entrySet()) {
pairs.add(new BasicNameValuePair(param.getKey(), param.getValue()));
}
HttpClient httpClient = null;
if (StringUtils.isBlank(ip)) {
httpClient = getSslHttpClient();
} else {
httpClient = getSslHttpClient(ip);
}
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(pairs, charSet));
return httpClient.execute(httpPost);
}
public static CloseableHttpClient getSslHttpClient() {
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", trustAllHttpsCertificates()).build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
HttpClientBuilder httpClientBuilder = HttpClients.custom();
httpClientBuilder.setConnectionManager(connectionManager);
CloseableHttpClient httpClient = httpClientBuilder.build();
return httpClient;
}
/**
* 设置DNS核心方法
* @param ip
* @return
*/
public static CloseableHttpClient getSslHttpClient(String ip) {
CloseableHttpClient httpClient = null;
synchronized (lock) {
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", trustAllHttpsCertificates()).build();
//核心:1. 创建MyDnsResolver对象
MyDnsResolver myDnsResolver = new MyDnsResolver(new HashMap<>());
//核心:2. 设置DNS
myDnsResolver.addResolve(HOST, ip);
//核心:3. 创建BasicHttpClientConnectionManager对象,指定MyDnsResolver
HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry, null, null, myDnsResolver);
log.info("Get httpclient by creating basichttpclientconnectionmanager and setting custom DNS, myDnsResolver: {}", myDnsResolver.toString());
HttpClientBuilder httpClientBuilder = HttpClients.custom();
//核心:4. httpClientBuilder设置BasicHttpClientConnectionManager对象
httpClientBuilder.setConnectionManager(connectionManager);
httpClient = httpClientBuilder.build();
}
return httpClient;
}
private static SSLConnectionSocketFactory trustAllHttpsCertificates() {
SSLConnectionSocketFactory socketFactory = null;
TrustManager[] trustAllCerts = new TrustManager[1];
TrustManager tm = new miTM();
trustAllCerts[0] = tm;
SSLContext sc = null;
try {
sc = SSLContext.getInstance("TLS");//sc = SSLContext.getInstance("TLS")
sc.init(null, trustAllCerts, null);
socketFactory = new SSLConnectionSocketFactory(sc, NoopHostnameVerifier.INSTANCE);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
return socketFactory;
}
private static class miTM implements TrustManager, X509TrustManager {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
//don't check
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
//don't check
}
}
}
- 使用方式:
直接调用SslHttpUtil的sendPost方法,指定URL、请求参数、IP 即可
public static void main(String[] args) throws Exception {
SslHttpUtil.sendPost("www.baidu.com/test.do", new HashMap<>(), "127.0.0.1");
}
两种方式对比
- 方式一是基于InetAddress类实现的DNS设置,是针对整个JVM全局的,也就是说在指定IP时设置了DNS,不指定IP时也必须设置一下DNS,否则将会使用上次设置的DNS发起请求,导致结果不符合预期。
- 第二种方式是针对HttpClient设置的,指定IP发起请求,创建httpClient时设置DNS,一次有效。当不指定IP发起请求时,会使用服务器host上的默认配置。