https post设置代理发送请求

本文主要是对http和https 发送post请求所做工具类, 方法中有两个参数:https(是否是https地址)和proxy(是否使用代理)。

http和https主要使用apache的基础jar包,代理地址可从配置文件中获取。好了,废话不多说,直接上代码:

1. https请求类

public class HttpProxyPost {
 private static Logger logger = LoggerFactory.getLogger(HttpProxyPost.class);
 private static PropertiesConfiguration config = PropertiesUtils.INSTANCE.getConfig();
 private static CloseableHttpClient client = null;
 public static String requestWithPost(String postUrl, JSONObject reqJson, Boolean https, Boolean proxy) {
  HttpResponse rsp = null;
  try {
   client = SSLClient.getHttpsClient(https);
  } catch (Exception e) {
   logger.error("获取httpCliet失败");
  }
  HttpPost post = new HttpPost(postUrl);
  if (proxy) {
   String proxyIP = config.getString("proxyIP");
   int proxyPort = Integer.parseInt(config.getString("proxyPort"));
   logger.info("使用代理发送请求:{}:{}", proxyIP, proxyPort);
   HttpHost proxyHost = new HttpHost(proxyIP, proxyPort);
   RequestConfig reqConfig = RequestConfig.custom().setProxy(proxyHost).build();
   post.setConfig(reqConfig);
  }
  StringEntity params = null;
  String rspStr = "";
  try {
   params = new StringEntity(reqJson.toString(), "utf-8");
   params.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
   params.setChunked(true);
   post.addHeader("content-type", "application/json");
   post.setEntity(params);
   rsp = client.execute(post);
   HttpEntity entity = rsp.getEntity();
   String rspString = EntityUtils.toString(entity, "utf-8");
   JSONObject rspJson = JSONObject.parseObject(rspString);
   logger.info("请求返回报文:{}", rspJson);
   rspStr = rspJson.toString();
  } catch (Exception e) {
   logger.info("外调异常::{}", e.getMessage());
  } finally {
   client.getConnectionManager().shutdown();
  }
  return rspStr;
 } 
}
2. 创建https client
public class SSLClient {
 private static HttpClientBuilder builder;
 public static CloseableHttpClient getHttpsClient(Boolean https)
   throws KeyManagementException, NoSuchAlgorithmException {
  if (builder == null) {
   builder = HttpClientBuilder.create();
  }
  if (!https) {
   return builder.build();
  } else {
   X509TrustManager tm = new X509TrustManager() {
    @Override
    public X509Certificate[] getAcceptedIssuers() {
     return null;
    }
    @Override
    public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
     // TODO Auto-generated method stub
    }
    @Override
    public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
     // TODO Auto-generated method stub
    }
   };
   SSLContext ctx = SSLContext.getInstance("TLS");
   ctx.init(null, new TrustManager[] { tm }, null);
   SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
   builder.setSSLSocketFactory(ssf);
  }
  return builder.build();
 }
 
posted on 2019-06-07 16:34  一季书生  阅读(5089)  评论(0编辑  收藏  举报