HttpClientUtil 封装方法
来源:互联网 发布:java多文件上传插件 编辑:程序博客网 时间:2024/06/11 01:31
package com.cat.common.http;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.security.KeyManagementException;import java.security.KeyStore;import java.security.KeyStoreException;import java.security.NoSuchAlgorithmException;import java.security.UnrecoverableKeyException;import java.security.cert.CertificateException;import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.Map.Entry;import javax.net.ssl.SSLContext;import org.apache.http.Header;import org.apache.http.HttpEntity;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.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.conn.ssl.SSLConnectionSocketFactory;import org.apache.http.conn.ssl.SSLContexts;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;import org.apache.http.impl.client.HttpClients;import org.apache.http.message.BasicHeader;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;import org.springframework.stereotype.Service;import com.cat.common.bean.EMsg;import com.cat.common.exception.RequestException;import com.cat.common.lang.RString;@Service("httpClientUtil")public class HttpClientUtil{ /** * 连接超时时间 */ private static int CONNECT_TIMEOUT = 10 * 1000; /** * 短时间连接超时时间 */ private static int SHORT_TIMEOUT = 5 * 1000; /** * 套接字超时时间 */ private static int SOCKET_TIMEOUT = 35 * 1000; /** * 连接池中 连接请求执行被阻塞的超时时间 */ private static int CONN_MANAGER_TIMEOUT = 10 * 1000; private CloseableHttpClient getHttpClient(boolean isShortTime){ int ctime = CONNECT_TIMEOUT; int stime = SOCKET_TIMEOUT; int cmtime = CONN_MANAGER_TIMEOUT; if(isShortTime){ //短时间快速响应 ctime = SHORT_TIMEOUT; stime = SHORT_TIMEOUT; cmtime = SHORT_TIMEOUT; } RequestConfig requestConfig = RequestConfig.custom() //设置连接到第三方服务的超时时间 .setConnectTimeout(ctime) //设置第三方服务传输数据的超时时间 .setSocketTimeout(stime) //设置从连接池获取连接超时时间 .setConnectionRequestTimeout(cmtime).build(); //设置重定向策略 //为大连接量考虑,设置重试次数为0,默认为3 CloseableHttpClient httpclient = HttpClients.custom().setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)).setDefaultRequestConfig(requestConfig).build(); return httpclient; } public String postHttplientJson(String url, String info) throws RequestException{ return postJson(url, info, false); } /** * 增加header头 * @param url * @param info * @param header * @return * @throws RequestException */ public String postHttplientJsonHeard(String url, String info, Map<String, String> header) throws RequestException{ return postJson(url, info, false, header, ""); } /** * 短时间快速响应,不然就超时断开,默认5秒 * @param url * @param info * @return * @throws RequestException */ public String postHttplientJsonShortTime(String url, String info) throws RequestException{ return postJson(url, info, true); } public String postJson(String url, String info, boolean isShortTime) throws RequestException{ return postJson(url, info, isShortTime, null, ""); } public String postJson(String url, String info, boolean isShortTime, Map<String, String> headers, String contentType) throws RequestException{ CloseableHttpResponse resp = null; InputStream instream = null; BufferedReader reader = null; CloseableHttpClient httpclient = null; try{ httpclient = getHttpClient(isShortTime); HttpPost httpPost = new HttpPost(url); StringEntity sentity = new StringEntity(info, "utf-8");// 解决中文乱码问题 if(RString.isNotBlank(info)){ httpPost.setEntity(sentity); } httpPost.setHeader("ContentType", "text/plain; charset=UTF-8"); sentity.setContentType("application/json;charset=UTF-8"); if(RString.isNotBlank(contentType)){ httpPost.setHeader("ContentType", contentType); sentity.setContentType(contentType); } if(headers != null){ for(Entry<String, String> entry : headers.entrySet()){ Header header = new BasicHeader(entry.getKey(), entry.getValue()); httpPost.addHeader(header); } } resp = httpclient.execute(httpPost); HttpEntity entity = resp.getEntity(); if(entity == null){ return ""; } instream = entity.getContent(); reader = new BufferedReader(new InputStreamReader(instream, "utf-8")); StringBuffer stringBuffer = new StringBuffer(); String str = ""; while((str = reader.readLine()) != null){ stringBuffer.append(str); } return stringBuffer.toString(); }catch(ClientProtocolException e){ e.printStackTrace(); throw new RequestException(EMsg.Http_Client_Error.code(), EMsg.Http_Client_Error.value(), e); }catch(IOException e){ e.printStackTrace(); throw new RequestException(EMsg.Http_Io_Error.code(), EMsg.Http_Io_Error.value(), e); }finally{ try{ httpclient.close(); resp.close(); instream.close(); reader.close(); }catch(Exception e){ e.printStackTrace(); } } } public String get(String url, boolean isShortTime) throws RequestException{ CloseableHttpResponse resp = null; InputStream instream = null; BufferedReader reader = null; CloseableHttpClient httpclient = null; try{ httpclient = getHttpClient(isShortTime); HttpGet httpGet = new HttpGet(url); resp = httpclient.execute(httpGet); HttpEntity entity = resp.getEntity(); if(entity == null){ return ""; } instream = entity.getContent(); reader = new BufferedReader(new InputStreamReader(instream, "utf-8")); StringBuffer stringBuffer = new StringBuffer(); String str = ""; while((str = reader.readLine()) != null){ stringBuffer.append(str); } return stringBuffer.toString(); }catch(ClientProtocolException e){ e.printStackTrace(); throw new RequestException(EMsg.Http_Client_Error.code(), EMsg.Http_Client_Error.value(), e); }catch(IOException e){ e.printStackTrace(); throw new RequestException(EMsg.Http_Io_Error.code(), EMsg.Http_Io_Error.value(), e); }finally{ try{ httpclient.close(); resp.close(); instream.close(); reader.close(); }catch(Exception e){ e.printStackTrace(); } } } /** * 需要加密执行的 * * @param url * @param xmlInfo * @return * @throws RequestException * @throws Exception */ public String postHttplientNeedSSL(String url, String xmlInfo, String cretPath, String mrchId) throws RequestException{ FileInputStream instream = null; CloseableHttpResponse response = null; CloseableHttpClient httpclient = null; // 选择初始化密钥文件格式 try{ KeyStore keyStore = KeyStore.getInstance("PKCS12"); // 得到密钥文件流 instream = new FileInputStream(new File(cretPath)); // 用商户的ID 来解读文件 keyStore.load(instream, mrchId.toCharArray()); // 用商户的ID 来加载 SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, mrchId.toCharArray()).build(); // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); // 用最新的httpclient 加载密钥 httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); StringBuffer ret = new StringBuffer(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new StringEntity(xmlInfo)); response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); if(entity != null){ BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent())); String text; while((text = bufferedReader.readLine()) != null){ ret.append(text); } } EntityUtils.consume(entity); return ret.toString(); }catch(KeyStoreException | FileNotFoundException | CertificateException | NoSuchAlgorithmException | KeyManagementException | UnrecoverableKeyException e){ e.printStackTrace(); throw new RequestException(EMsg.Http_Client_Error.code(), EMsg.Http_Client_Error.value(), e); }catch(IOException e){ e.printStackTrace(); throw new RequestException(EMsg.Http_Client_Error.code(), EMsg.Http_Client_Error.value(), e); }finally{ try{ httpclient.close(); response.close(); instream.close(); }catch(Exception e){ e.printStackTrace(); } } } public String postMap(String url, Map<String, String> headers, Map<String, String> params) throws RequestException{ return postMap(url, false, headers, params); } /** * 参数为 key-value * @param url * @param isShortTime * @param headers * @param params * @return * @throws RequestException */ public String postMap(String url, boolean isShortTime, Map<String, String> headers, Map<String, String> params) throws RequestException{ CloseableHttpResponse resp = null; InputStream instream = null; BufferedReader reader = null; CloseableHttpClient httpclient = null; try{ httpclient = getHttpClient(isShortTime); HttpPost httpPost = new HttpPost(url); httpPost.setHeader("ContentType", "text/plain; charset=UTF-8"); if(headers != null){ for(Entry<String, String> entry : headers.entrySet()){ Header header = new BasicHeader(entry.getKey(), entry.getValue()); httpPost.addHeader(header); } } //装填参数 List<NameValuePair> nvps = new ArrayList<NameValuePair>(); if(params != null){ for(String key : params.keySet()){ nvps.add(new BasicNameValuePair(key, params.get(key))); } } //设置参数到请求对象中 httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8")); resp = httpclient.execute(httpPost); HttpEntity entity = resp.getEntity(); if(entity == null){ return ""; } instream = entity.getContent(); reader = new BufferedReader(new InputStreamReader(instream, "utf-8")); StringBuffer stringBuffer = new StringBuffer(); String str = ""; while((str = reader.readLine()) != null){ stringBuffer.append(str); } return stringBuffer.toString(); }catch(ClientProtocolException e){ e.printStackTrace(); throw new RequestException(EMsg.Http_Client_Error.code(), EMsg.Http_Client_Error.value(), e); }catch(IOException e){ e.printStackTrace(); throw new RequestException(EMsg.Http_Io_Error.code(), EMsg.Http_Io_Error.value(), e); }finally{ try{ httpclient.close(); resp.close(); instream.close(); reader.close(); }catch(Exception e){ e.printStackTrace(); } } }}
阅读全文
0 0
- HttpClientUtil 封装方法
- HttpClientUtil封装2
- HttpClientUtil
- HttpClientUtil
- HttpClientUtil
- HttpClientUtil
- HttpClientUtil
- HttpClientUtil
- HttpClientUtil
- HttpClientUtil
- HttpClientUtil
- httpclientutil
- HttpClientUtil
- HttpClientUtil
- HttpClientUtil
- 接口自动化之封装httpclientUtil类
- HttpClientUtil工具
- 封装方法
- 秒杀 简解
- leetcode--Pascal's Triangle II
- poj2288 状压dp
- CentOS安装solr 4.10.3
- 集成电路中的测试概述(一)
- HttpClientUtil 封装方法
- Centos7下搭载邮件服务器
- to
- [Leetcode] 338. Counting Bits 解题报告
- [SDUT](3361) 数据结构实验之图论四:迷宫探索 ---DFS(图)
- Android Studio频繁假死解决方法记录
- 生产者和消费者的经典问题 java编程实现
- ios-依赖系统语言的应该程序名字的国际化
- 图论--2017暑期第四周专题