话不多说,直接上代码:
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
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.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* @Description:
*/
public class HttpClientProxyUtil {
public static void main(String[] args) throws Exception {
String url ="https://www.baidu.com";
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpClient httpsclient = createSSLClientDefault();
//HttpPost httpPost = new HttpPost(url);
HttpGet httpPost = new HttpGet(url);
if(url.contains("外网域名")||url.contains("https")) {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope("代理服务器域名", 代理服务器端口号), // 认证范围
new UsernamePasswordCredentials("代理服务器认证用户名", "代理服务器认证密码")); // 认证用户名和密码
httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
//定义代理,scheme默认http
HttpHost proxy = new HttpHost("代理服务器域名", 代理服务器端口号,scheme );
//设置代理
RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
//使用配置
httpPost.setConfig(config);
}
try {
//设置请求头
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
setHeaders(httpPost, headers);
JSONObject jsonParams = new JSONObject();
//设置请求体
setBodyByJson(httpPost, jsonParams);
System.out.println("执行请求:" + httpPost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
System.out.println("----------------------------------------");
System.out.println("响应:" + response.getStatusLine());
System.out.println("内容:" + EntityUtils.toString(response.getEntity()));
System.out.println("----------------------------------------");
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
/**
* json方式设置请求体
*
* @param httpRequest 请求对象
* @param jsonParams 请求体
*/
public static void setHeaders(HttpRequestBase httpRequest, Map<String, String> headers) {
if (null != headers && headers.size() != 0) {
Iterator<Map.Entry<String, String>> iterator = headers.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
httpRequest.addHeader(entry.getKey(), entry.getValue());
}
}
}
/**
* json方式设置请求体
*
* @param httpRequest 请求对象
* @param jsonParams 请求体
*/
public static void setBodyByJson(HttpEntityEnclosingRequestBase httpRequest, JSONObject jsonParams) {
if (null != jsonParams) {
StringEntity entity = new StringEntity(jsonParams.toString(), StandardCharsets.UTF_8);
entity.setContentEncoding("utf-8");
entity.setContentType("application/json");
httpRequest.setEntity(entity);
}
}
/**
* javax.net.ssl.SSLException:Unrecognized SSL message,plaintext connection
* @return
*/
public static CloseableHttpClient createSSLClientDefault() {
try {
//使用 loadTrustMaterial() 方法实现一个信任策略,信任所有证书
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
// 信任所有
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
//NoopHostnameVerifier类: 作为主机名验证工具,实质上关闭了主机名验证,它接受任何
//有效的SSL会话并匹配到目标主机。
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}
}
最后
以上就是乐观大船最近收集整理的关于httpclient 访问外网接口代理设置的全部内容,更多相关httpclient内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复