使用HttpClient4.3.1模拟Http请求与无信任证书访问Https

来源:互联网 发布:淘宝引流宝怎么设置 编辑:程序博客网 时间:2024/06/05 22:19
package com.paic.pmit.core.util;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Map.Entry;import java.util.Set;import org.apache.commons.httpclient.HttpStatus;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.config.RequestConfig;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClientBuilder;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;import org.apache.log4j.Logger;import com.paic.pafa.app.biz.service.BusinessServiceException;import com.paic.pmit.core.biz.service.impl.AbstractInvokeGroovy;/** * 模拟Http请求 * @author:EX-WANGYIDE001 * @date:2016-10-1上午10:29:18 *-------------------- *修改记录,含日期,作者,修改内容 */public class public_equipment_HttpClientUtils extends AbstractInvokeGroovy  {Logger logger = Logger.getLogger(this.getClass());/** * 发送http请求 * @author:EX-WANGYIDE001 * @date:2016-10-1上午10:29:14 * @param url 请求URL * @param parameter请求参数 * @param requestCharset 编码格式 * @return * @throws BusinessServiceException */public String sendHttpRequest(String url, Map<String, String> parameter, String requestCharset) throws BusinessServiceException {logger.info("处理Http请求:"+url);long start = System.currentTimeMillis(); String result = null;CloseableHttpClient http = null;try {//创建HttpClient//HttpHost proxy = new HttpHost("10.36.232.126",8080);代理RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(60000).build();HttpClientBuilder builder = HttpClientBuilder.create();http = builder.build();//http = createSSLClientDefault();//post请求HttpPost httpPost = new HttpPost(url);httpPost.setConfig(config);//参数队列httpPost.setEntity(new UrlEncodedFormEntity(parameterConvert(parameter),requestCharset));//执行请求HttpResponse response = http.execute(httpPost);//响应处理int httpStatus = response.getStatusLine().getStatusCode();if (httpStatus == HttpStatus.SC_OK){HttpEntity entity = response.getEntity();if(entity != null){result = EntityUtils.toString(entity, requestCharset);logger.info("返回参数:"+result);}}else{throw new BusinessServiceException("服务方接口响应异常, httpStatus: " + httpStatus);}} catch (UnsupportedEncodingException e) {logger.error("http请求参数处理异常",e);throw new BusinessServiceException("http请求参数处理异常");} catch (ClientProtocolException e) {logger.error("http请求发生HTTP异常",e);throw new RuntimeException("http请求发生HTTP异常");} catch (IOException e) {logger.error("http请求发生IO异常",e);throw new RuntimeException("http请求发生IO异常");} finally{logger.info("耗时: " + (System.currentTimeMillis() - start) + " 毫秒");if(http!=null){try {http.close();} catch (IOException e) {logger.error("释放资源  close error:"+e);}}}return result;}/** * 转换参数 * @author:EX-WANGYIDE001 * @date:2016-10-1下午2:59:37 * @param parameter * @return */private List<NameValuePair> parameterConvert(Map<String,String> parameter){List<NameValuePair> results = new ArrayList<NameValuePair>(parameter.size());Set<Entry<String, String>> entrySet = parameter.entrySet();for (Iterator<Entry<String, String>> iter = entrySet.iterator(); iter.hasNext();) {Entry<String, String> entry = iter.next();results.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));}return results;}/** * 处理Https请求证书 * @author:EX-WANGYIDE001 * @date:2016-10-1下午3:50:34 * @return *//*private CloseableHttpClient createSSLClientDefault(){try {             SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {                 //信任所有证书                 public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {                     return true;                 }             }).build();             SSLConnectionSocketFactory sslFactory = new SSLConnectionSocketFactory(sslContext);             return HttpClients.custom().setSSLSocketFactory(sslFactory).build();         } catch (Exception e) {         logger.error("处理Https证书异常",e);         }         return  HttpClients.createDefault();}*//** * 测试方法 * @author:EX-WANGYIDE001 * @date:2016-10-2上午9:58:51 * @param args * @throws Exception *//*public static void main(String args[]) throws Exception {public_equipment_HttpClientUtils http = new public_equipment_HttpClientUtils();Map<String,String> parameter = new HashMap<String,String>();parameter.put("credentials", "123456123");http.sendHttpRequest("测试地址", parameter, "UTF-8");}*/}


0 0
原创粉丝点击