httpclient 访问外网接口代理设置

话不多说,直接上代码:

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();

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值