封装HttpClient4.x工具
添加依赖
<!--HttpClient4.x--> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.5.13</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> </dependency> <!--gson 工具,封装http的时候用--> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.6</version> </dependency>
工具类
package com.ybchen.utils; import com.google.gson.Gson; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.config.RequestConfig; 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.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.util.HashMap; import java.util.Map; /** * @Description:封装http get post * @Author:chenyanbin * @Date:2021/3/12 下午1:31 * @Versiion:1.0 */ public class HttpUtils { private static final Gson gson = new Gson(); /** * get方法 * * @param url url地址 * @return */ public static Map<String, Object> doGet(String url) { Map<String, Object> map = new HashMap<>(); CloseableHttpClient httpClient = HttpClients.createDefault(); RequestConfig requestConfig = RequestConfig.custom() //建立连接时间 .setConnectTimeout(5000) //请求超时时间 .setConnectionRequestTimeout(5000) //socket时间 .setSocketTimeout(5000) //允许重定向 .setRedirectsEnabled(true) .build(); HttpGet httpGet = new HttpGet(url); httpGet.setConfig(requestConfig); try { //发送请求 HttpResponse httpResponse = httpClient.execute(httpGet); if (httpResponse.getStatusLine().getStatusCode() == 200) { String jsonResult = EntityUtils.toString(httpResponse.getEntity()); map = gson.fromJson(jsonResult, map.getClass()); } } catch (Exception e) { e.printStackTrace(); } finally { try { httpClient.close(); } catch (Exception e) { e.printStackTrace(); } } return map; } /** * post方法 * @param url 请求url * @param data 数据 * @param timeout 超时时间,毫秒 * @return */ public static String doPost(String url, String data, int timeout) { CloseableHttpClient httpClient = HttpClients.createDefault(); //超时设置 RequestConfig requestConfig = RequestConfig.custom() //建立连接时间 .setConnectTimeout(timeout) //请求超时时间 .setConnectionRequestTimeout(timeout) //socket时间 .setSocketTimeout(timeout) //允许重定向 .setRedirectsEnabled(true) .build(); HttpPost httpPost = new HttpPost(url); //设置头信息 httpPost.addHeader("Content-Type", "text/html;chartset=utf8"); httpPost.setConfig(requestConfig); //使用字符串传参 if (data != null && data instanceof String) { StringEntity stringEntity = new StringEntity(data, "UTF-8"); httpPost.setEntity(stringEntity); } try { //发送请求 CloseableHttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); if (httpResponse.getStatusLine().getStatusCode() == 200) { String result = EntityUtils.toString(httpEntity); return result; } } catch (Exception e) { e.printStackTrace(); } finally { try { httpClient.close(); } catch (Exception e) { e.printStackTrace(); } } return null; } }
http连接池工具类
import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.client.config.RequestConfig; 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.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.util.EntityUtils; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.Map; /** * 带线程池http工具类 * @author: chenyanbin 2022-12-09 17:21 */ @Slf4j public class HttpPoolUtil { private static PoolingHttpClientConnectionManager cm; private static CloseableHttpClient httpClient; static { cm = new PoolingHttpClientConnectionManager(); // 整个连接池最大连接数 cm.setMaxTotal(100); // 每路由最大连接数,默认值是2 cm.setDefaultMaxPerRoute(5); httpClient = HttpClients.custom().setConnectionManager(cm).build(); } /** * 获取网络图片转成字节流 * * @param strUrl 完整图片地址 * @return 图片资源数组 */ public static byte[] getNetImgByUrl(String strUrl) { try { URL url = new URL(strUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(2 * 1000); // 通过输入流获取图片数据 InputStream inStream = conn.getInputStream(); // 得到图片的二进制数据 byte[] btImg = readInputStream(inStream); return btImg; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 从输入流中获取字节流数据 * * @param inStream 输入流 * @return 图片流 */ private static byte[] readInputStream(InputStream inStream) throws Exception { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); // 设置每次读取缓存区大小 byte[] buffer = new byte[1024 * 10]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } inStream.close(); return outStream.toByteArray(); } /** * get方法 * * @param url url地址 * @return */ public static String doGet(String url) { RequestConfig requestConfig = RequestConfig.custom() //建立连接时间 .setConnectTimeout(5000) //请求超时时间 .setConnectionRequestTimeout(5000) //socket时间 .setSocketTimeout(5000) //允许重定向 .setRedirectsEnabled(true) .build(); HttpGet httpGet = new HttpGet(url); httpGet.setConfig(requestConfig); try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) { //发送请求 if (httpResponse.getStatusLine().getStatusCode() == 200) { String jsonResult = EntityUtils.toString(httpResponse.getEntity()); return jsonResult; } } catch (Exception e) { log.error("doGet url:{},发送异常:{}", url, e); } return null; } /** * post方法 * * @param url 请求url * @param data 数据 * @param timeout 超时时间,毫秒 * @param contentType 接口响应类型 * @param headerMap header Map * @return */ public static String doPost(String url, String data, int timeout, String contentType, Map<String, String> headerMap) { //超时设置 RequestConfig requestConfig = RequestConfig.custom() //建立连接时间 .setConnectTimeout(timeout) //请求超时时间 .setConnectionRequestTimeout(timeout) //socket时间 .setSocketTimeout(timeout) //允许重定向 .setRedirectsEnabled(true) .build(); HttpPost httpPost = new HttpPost(url); //设置头信息 httpPost.addHeader("Content-Type", StringUtils.isBlank(contentType) ? "application/json" : contentType); headerMap.forEach(httpPost::setHeader); httpPost.setConfig(requestConfig); //使用字符串传参 if (StringUtils.isNotBlank(data)) { StringEntity stringEntity = new StringEntity(data, "UTF-8"); httpPost.setEntity(stringEntity); } //发送请求 try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) { HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { String result = EntityUtils.toString(httpEntity); return result; } } catch (Exception e) { log.error("doPost url:{},data:{},发生异常:{}", url, data, e); } return null; } public static void main(String[] args) { for (int i = 0; i < 10; i++) { String content = doGet("http://baidu.com"); System.err.println(">>>>>>>>" + content); } } }
post表单方式发送
/** * post 表单方式 * @param url url * @param dataMap 表单参数 * @return */ public static String postWithParamsForString(String url, Map<String, String> dataMap){ List<NameValuePair> params = new ArrayList<>(); CloseableHttpClient httpClient = HttpClients.createDefault(); //超时设置 RequestConfig requestConfig = RequestConfig.custom() //建立连接时间 .setConnectTimeout(5000) //请求超时时间 .setConnectionRequestTimeout(5000) //socket时间 .setSocketTimeout(5000) //允许重定向 .setRedirectsEnabled(true) .build(); HttpPost httpPost = new HttpPost(url); httpPost.setConfig(requestConfig); try { if (dataMap != null && dataMap.size() != 0) { for (Map.Entry<String, String> entry : dataMap.entrySet()) { params.add(new NameValuePair() { @Override public String getName() { return entry.getKey(); } @Override public String getValue() { return entry.getValue(); } }); } } httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8)); httpPost.setHeader("Content-type", "application/x-www-form-urlencoded"); HttpResponse response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); if (HttpURLConnection.HTTP_OK == statusCode) { HttpEntity entity = response.getEntity(); String result =EntityUtils.toString(entity); return result; } }catch (Exception e){ e.printStackTrace(); } return null; }

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号