java的http请求工具类HttpClientUtils怎么使用
发表于:2025-01-31 作者:千家信息网编辑
千家信息网最后更新 2025年01月31日,本篇内容主要讲解"java的http请求工具类HttpClientUtils怎么使用",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"java的http请求工
千家信息网最后更新 2025年01月31日java的http请求工具类HttpClientUtils怎么使用
本篇内容主要讲解"java的http请求工具类HttpClientUtils怎么使用",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"java的http请求工具类HttpClientUtils怎么使用"吧!
import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import org.apache.commons.collections.MapUtils;import org.apache.commons.lang.StringUtils;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.http.Header;import org.apache.http.HttpEntity;import org.apache.http.HttpStatus;import org.apache.http.NameValuePair;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.HttpEntityEnclosingRequestBase;import org.apache.http.client.methods.HttpPost;import org.apache.http.client.methods.HttpRequestBase;import org.apache.http.config.Registry;import org.apache.http.config.RegistryBuilder;import org.apache.http.conn.HttpClientConnectionManager;import org.apache.http.conn.socket.ConnectionSocketFactory;import org.apache.http.conn.ssl.AllowAllHostnameVerifier;import org.apache.http.conn.ssl.SSLConnectionSocketFactory;import org.apache.http.conn.ssl.SSLContexts;import org.apache.http.conn.ssl.X509HostnameVerifier;import org.apache.http.entity.StringEntity;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.util.EntityUtils;import org.springframework.util.CollectionUtils;import javax.net.ssl.SSLContext;import javax.net.ssl.TrustManager;import javax.net.ssl.X509TrustManager;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.net.SocketTimeoutException;import java.net.URLEncoder;import java.security.cert.CertificateException;import java.security.cert.X509Certificate;import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.Set;/** * */public class HttpClientUtils { private static Log logger = LogFactory.getLog(HttpClientUtils.class); private static PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(); private static CloseableHttpClient httpClient = null; private static final int DEFAULT_MAX_TOTAL_CONNECTION = 1024; private static final int DEFAULT_MAX_PER_ROUTE = 300; private static final String DEFAULT_ENCODING = "UTF-8"; // 默认的查询参数及返回结果的字符串编码 private static final String CONTENT_TYPE_TEXT_XML = "application/xml"; // 默认的查询参数及返回结果的字符串编码 private static final String APPLICATION_XML = "text/xml"; // 默认的查询参数及返回结果的字符串编码 private static final int DEFAULT_CONNECTION_TIME_OUT = 60000; // 默认连接超时时间, // 60秒 private static final int DEFAULT_READ_TIME_OUT = 200000; // 默认响应超时时间, 60秒 public static JSONObject custRespHeader = new JSONObject(); static { poolingHttpClientConnectionManager.setMaxTotal(DEFAULT_MAX_TOTAL_CONNECTION); poolingHttpClientConnectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_PER_ROUTE); httpClient = HttpClients.custom().setConnectionManager(poolingHttpClientConnectionManager).build(); } private HttpClientUtils() { } /** * @param url * @param params * @param encode * @param connectTimeout * @param readTimeout * @return */ public static String invokeGet(String url, Mapparams, String encode, int connectTimeout, int readTimeout) { if (connectTimeout <= 0) { return null; } RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeout) .setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectTimeout).build(); String responseString; String requestUrl; try { requestUrl = buildRequestUrl(url, params); } catch (UnsupportedEncodingException e) { logger.error("encode http get params error, params is " + params, e); return ""; } HttpPost httpGet = new HttpPost(requestUrl); httpGet.setHeader("Connection", "close"); httpGet.setConfig(requestConfig); responseString = doRequest(httpGet, encode); return responseString; } /** * @param requestUrl * @param params * @return */ public static String invokePost(String requestUrl, Map params) { return invokePost(requestUrl, params, null, null, DEFAULT_ENCODING, DEFAULT_CONNECTION_TIME_OUT, DEFAULT_READ_TIME_OUT); } public static String invokePost(String requestUrl, Map params,Map requestHeader) { return invokePost(requestUrl, params, requestHeader, null, DEFAULT_ENCODING, DEFAULT_CONNECTION_TIME_OUT, DEFAULT_READ_TIME_OUT); } /** * @param requestUrl * @param requestHeader * @param requestBody * @return */ public static String invokePost(String requestUrl, Map requestHeader, String requestBody) { return invokePost(requestUrl, null, requestHeader, requestBody, DEFAULT_ENCODING, DEFAULT_CONNECTION_TIME_OUT, DEFAULT_READ_TIME_OUT); } /** * @param requestUrl * @param params * @param requestHeader * @param requestBody * @param encode * @param connectTimeout * @param readTimeout * @return */ public static String invokePost(String requestUrl, Map params, Map requestHeader, String requestBody, String encode, int connectTimeout, int readTimeout) { RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeout) .setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectTimeout).build(); String responseString; HttpPost httpPost = new HttpPost(requestUrl); httpPost.setConfig(requestConfig); if (MapUtils.isNotEmpty(requestHeader)) { for (Map.Entry entry : requestHeader.entrySet()) { httpPost.addHeader(entry.getKey(), entry.getValue()); } } buildPostParams(httpPost, params, requestBody, encode); responseString = doRequest(httpPost, encode); return responseString; } /** * @param httpPost * @param params * @param requestBody * @param encode */ private static void buildPostParams(HttpPost httpPost, Map params, String requestBody, String encode) { try { if (MapUtils.isNotEmpty(params)) { List nameValuePairs = new ArrayList (); for (Map.Entry entry : params.entrySet()) { String value = null; if (entry.getValue() instanceof String) { value = (String) entry.getValue(); } else { value = JSON.toJSONString(entry.getValue()); } nameValuePairs.add(new BasicNameValuePair(entry.getKey(), value)); } httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, encode)); } if (StringUtils.isNotBlank(requestBody)) { httpPost.setEntity(new StringEntity(requestBody, encode)); } } catch (UnsupportedEncodingException e) { logger.error("HttpClientUtils.buildPostParams error, params = " + params, e); } } /** * @param httpRequestBase * @param encode * @return */ private static String doRequest(HttpRequestBase httpRequestBase, String encode) { String responseString = null; try { long start = System.currentTimeMillis(); CloseableHttpResponse response = httpClient.execute(httpRequestBase); logger.info("HttpClientUtils Begin Invoke: " + httpRequestBase.getURI() + ", cost time " + (System.currentTimeMillis() - start) + " ms"); try { Header[] headers = response.getHeaders("isLogin"); if(headers!=null && headers.length>0){ custRespHeader.put(headers[0].getName(),headers[0].getValue()); } HttpEntity entity = response.getEntity(); try { if (entity != null) { responseString = EntityUtils.toString(entity, encode); } } finally { if (entity != null) { entity.getContent().close(); } } } catch (Exception e) { e.printStackTrace(); logger.error(String.format("[HttpClientUtils.doRequest] get response error, url:%s", httpRequestBase.getURI()), e); responseString = ""; } finally { if (response != null) { response.close(); } } } catch (SocketTimeoutException e) { e.printStackTrace(); logger.error(String.format("[HttpClientUtils.doRequest] invoke get timout error, url:%s", httpRequestBase.getURI()), e); responseString = ""; } catch (Exception e) { e.printStackTrace(); logger.error( String.format("[HttpClientUtils.doRequest] invoke get error, url:%s", httpRequestBase.getURI()), e); responseString = ""; } finally { httpRequestBase.releaseConnection(); } logger.info("HttpClientUtils response : " + responseString); return responseString; } /** * @param url * @param params * @return * @throws UnsupportedEncodingException */ private static String buildRequestUrl(String url, Map params) throws UnsupportedEncodingException { if (CollectionUtils.isEmpty(params)) { return url; } StringBuilder requestUrl = new StringBuilder(); requestUrl.append(url); int i = 0; for (Map.Entry entry : params.entrySet()) { if (i == 0) { requestUrl.append("?"); } requestUrl.append(entry.getKey()); requestUrl.append("="); String value = entry.getValue(); requestUrl.append(URLEncoder.encode(value, "UTF-8")); requestUrl.append("&"); i++; } requestUrl.deleteCharAt(requestUrl.length() - 1); return requestUrl.toString(); } public static void setStringParams(HttpPost httpost, Map params) { List nvps = new ArrayList (); Set keySet = params.keySet(); for (String key : keySet) { nvps.add(new BasicNameValuePair(key, params.get(key).toString())); } try { httpost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8")); } catch (UnsupportedEncodingException e) { } } /** * @param httpRequest * @param entity * @param * @return */ private static String sendRequest(HttpRequestBase httpRequest, HttpEntity entity) { httpRequest.setHeader("User-Agent", "okHttp"); if (httpRequest instanceof HttpEntityEnclosingRequestBase) {// checkArgument(null!=entity,"HttpEntity请求体不能为空"); ((HttpEntityEnclosingRequestBase) httpRequest).setEntity(entity); } //忽略证书 SSLContext sslContext = SSLContexts.createDefault(); X509TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; try { sslContext.init(null, new TrustManager[]{tm}, null); } catch (Exception ex) { ex.printStackTrace(); } X509HostnameVerifier hostnameVerifier = new AllowAllHostnameVerifier(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); Registry r = RegistryBuilder. create() .register("https", sslsf) .build(); HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r); CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build(); CloseableHttpResponse response = null; String resString = null; try { response = httpClient.execute(httpRequest); HttpEntity resEntity = response.getEntity(); int statusCode = response.getStatusLine().getStatusCode(); resString = EntityUtils.toString(resEntity, "UTF-8"); System.err.println(statusCode); if (statusCode != HttpStatus.SC_OK) { System.out.println("响应码状态不是200"); } return resString; } catch (Exception e) { throw new RuntimeException(resString, e); } finally { try { if (response != null) { response.close(); } if (httpRequest != null) { httpRequest.releaseConnection(); } if (httpClient != null) { httpClient.close(); } } catch (IOException e) { throw new RuntimeException(e); } } }}
调用示例:
public static void delAll(){ String url = path+"test/test/deleteAll"; Map map = new HashMap<>(); String str = HttpClientUtils.invokePost(url,map); System.out.println("delAll.str="+str); }
到此,相信大家对"java的http请求工具类HttpClientUtils怎么使用"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
UTF-8
查询
工具
参数
字符
字符串
结果
编码
内容
时间
学习
实用
更深
兴趣
实用性
实际
操作简单
方法
更多
朋友
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
成都联想软件开发方向
网络安全拥有强烈的使命感
哈尔滨java软件开发
江苏省网络安全工程专业人才
软件开发术语pm
高新技术企业培育数据库
陕西网络安全如何
软件开发财务明细表设计
服务器上安装pve
百度自研分布式数据库应用
网御星云二手服务器
坎德拉是基于什么软件开发的
世界两台服务器在哪
福建计算机软件开发培训
网络技术入股合同
琼海市手机软件开发
智能网络技术是什么意思
管道数据库
联想服务器虚拟化哪家便宜
信息科技开展网络安全宣讲
长三角网络安全海报大赛
网络安全专业学校排兄
北京音频管理服务器价格
数据库系统概论录入数据
厦门 网络安全 上市
数据库的安全机制包括_
香港阿里云服务器去杭州可以调吗
南山区品质网络技术开发分类
嵌入式软件开发分为底层驱动
大型企业有几台dhcp服务器