代码片段: httpclient-HttpPostEntity

package com.hand.util; import java.io.IOException; import java.io.InputStream; import java.security.cert.CertificateException; import java.util.ArrayList; import java.ut...
<pre>package com.hand.util; import java.io.IOException; import java.io.InputStream; import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; 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.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.ssl.SSLContexts; import org.apache.http.util.EntityUtils; import org.quartz.core.SampledStatistics; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.event.PublicInvocationEvent; import org.springframework.stereotype.Component; import org.springframework.util.Assert; import com.helioscloud.middleware.service.MidConfigurationService; import net.sf.json.JSONObject; @Component public class HttpPostEntity { private static final Logger logger = LoggerFactory.getLogger(HttpPostEntity.class); public static CloseableHttpClient httpclient = null; static{ SSLContext sslContext; try { sslContext = createIgnoreVerifySSL(); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", new SSLConnectionSocketFactory(sslContext)).build(); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager( socketFactoryRegistry); HttpClients.custom().setConnectionManager(connManager); SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory( SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(), NoopHostnameVerifier.INSTANCE); httpclient = HttpClients.custom().setSSLSocketFactory(scsf).build(); // 创建自定义的httpclient对象 //httpclient = HttpClients.custom().setConnectionManager(connManager).build(); } catch (Exception e) { logger.error("实现一个X509TrustManager接口,用于绕过验证异常",e); } } public static SSLContext createIgnoreVerifySSL() throws Exception { SSLContext sc = SSLContext.getInstance("SSLv3"); // 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法 X509TrustManager trustManager = new X509TrustManager() { @Override public void checkClientTrusted( java.security.cert.X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { } @Override public void checkServerTrusted( java.security.cert.X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } }; sc.init(null, new TrustManager[] { trustManager }, null); return sc; } @SuppressWarnings("unchecked") public <T> T doPost(Map<String, Object> reqMap,String url,Class<T> clazz){ Assert.notNull(reqMap, " request data must not be null "); Assert.notNull(url," request url must not be null "); HttpPost httpPost = new HttpPost(url); //添加参数 List<NameValuePair> param = new ArrayList<>(); Iterator<Entry<String, Object>> iterator = reqMap .entrySet().iterator(); while (iterator.hasNext()) { Entry<String, Object> next = iterator.next(); param.add(new BasicNameValuePair(next.getKey(), String.valueOf(next.getValue()))); } try { HttpEntity urlEncodedFormEntity = new UrlEncodedFormEntity(param, "utf-8"); httpPost.setEntity(urlEncodedFormEntity); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); httpPost.setHeader("Authorization", "Basic ZGNmNjg3YzAtNTVkMC00MTIwLWE0ZTMtN2YxYWQ2MWYwYTgyOk5qWmpZVFZsWm1NdE9HWXdaUzAwTnpKakxXRXlNekl0WXpJMFlUVTNNMlkwWmpBeQ=="); CloseableHttpResponse response = httpclient.execute(httpPost); if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); Assert.notNull(entity,"获取的数据为null"); if (clazz == JSONObject.class ) { String string = EntityUtils.toString(entity,"utf-8"); EntityUtils.consume(entity); return (T)JSONObject.fromObject(string); }else if (clazz == InputStream.class) { return (T)entity.getContent(); } } } catch (Exception e) { logger.error("http post method error",e); } return null; } } </pre>
  • 发表于 2018-07-07 14:00
  • 阅读 ( 261 )
  • 分类:代码片段

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除