基于apache httpClient 的post,get工具类

该代码段展示了一个Java的HttpClient工具类,实现了并发安全的HTTP请求,信任所有证书,自动释放闲置连接,并对连接数进行了限制。主要功能包括POST和GET方法,支持JSON数据提交及文件上传。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 功能
    • 并发安全,可以多线程使用
    • 信任所有证书(内网访问没问题,访问外部链接可能有安全风险)
    • 自动释放一段时间不活跃的连接,默认10秒
    • 默认每个主机2个连接,最多20个连接
  2. 代码
package common;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.apache.commons.io.IOUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MIME;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * 基于httpclient 的工具类
 * 
 * @Description:
 * @author wangzhiyue
 * @date 2024/06/20 15:13:11
 */
public class HttpClientUtil {
	/** 默认响应超时时间毫秒 */
	public static int SO_TIME_OUT = 10000;
	/** 默认连接超时时间毫秒 */
	public static int CONNECTION_TIME_OUT = 2000;

	private static CloseableHttpClient client = null;
	static {
		HttpClientBuilder builder = HttpClients.custom();
		builder.evictExpiredConnections();
		builder.setMaxConnTotal(50);
		builder.setMaxConnPerRoute(50);
		client = builder.build();
	}

	/**
	 * form 表单请求
	 * 
	 * @param url
	 * @param paras
	 * @param charset
	 * @param connectTime
	 * @param timeCout
	 * @return
	 * @author wangzhiyue
	 * @date 2024/06/20 16:11:09
	 */
	public static String post(String url, Map<String, String> paras, Charset charset, int connectTime, int timeCout) {
		String r = "";
		try {
			HttpPost httpPost = new HttpPost(url);
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			if (paras != null) {
				for (Map.Entry<String, String> e : paras.entrySet()) {
					nvps.add(new BasicNameValuePair(e.getKey(), e.getValue()));
				}
			}
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, charset));
			RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTime).setSocketTimeout(timeCout).build();
			httpPost.setConfig(config);
			try (CloseableHttpResponse response = client.execute(httpPost)) {
				HttpEntity entity = response.getEntity();
				r = EntityUtils.toString(entity, charset);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

		return r;
	}

	/**
	 * json 请求
	 * 
	 * @param url
	 * @param json
	 * @param charset
	 * @param connectTimeout
	 * @param timeCout
	 * @return
	 * @author wangzhiyue
	 * @date 2024/06/20 16:11:29
	 */
	public static String postJson(String url, String json, Charset charset, int connectTimeout, int timeCout) {
		String r = "";
		try {
			HttpPost httpPost = new HttpPost(url);
			httpPost.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
			RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(timeCout).build();
			httpPost.setConfig(config);
			try (CloseableHttpResponse response = client.execute(httpPost)) {
				HttpEntity entity = response.getEntity();
				r = EntityUtils.toString(entity, charset);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return r;
	}

	/**
	 * get请求
	 * 
	 * @param urlvalue
	 * @param connectTimeout
	 * @param timeCout
	 * @return
	 * @author wangzhiyue
	 * @date 2024/06/20 16:11:58
	 */
	public static String get(String urlvalue, Integer connectTimeout, Integer timeCout) {
		String r = "";
		try {
			HttpGet httpGet = new HttpGet(urlvalue);
			RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(timeCout).build();
			httpGet.setConfig(config);
			try (CloseableHttpResponse response = client.execute(httpGet)) {
				HttpEntity entity = response.getEntity();
				r = EntityUtils.toString(entity, StandardCharsets.UTF_8);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

		return r;
	}

	/**
	 * get 请求
	 * 
	 * @param urlvalue
	 * @return
	 * @author wangzhiyue
	 * @date 2024/06/20 16:12:16
	 */
	public static String get(String urlvalue) {
		return get(urlvalue, CONNECTION_TIME_OUT, SO_TIME_OUT);
	}

	/**
	 * 下载内容
	 * 
	 * @param urlvalue
	 * @return
	 * @author wangzhiyue
	 * @date 2024/06/20 16:12:35
	 */
	public static byte[] download(String urlvalue) {
		byte[] r = null;
		try {
			HttpGet httpGet = new HttpGet(urlvalue);
			RequestConfig config = RequestConfig.custom().setConnectTimeout(CONNECTION_TIME_OUT).setSocketTimeout(SO_TIME_OUT).build();
			httpGet.setConfig(config);
			try (CloseableHttpResponse response = client.execute(httpGet)) {
				HttpEntity entity = response.getEntity();
				InputStream infos = entity.getContent();
				System.out.println(infos.available());
				ByteArrayOutputStream bs = new ByteArrayOutputStream(infos.available());
				IOUtils.copy(entity.getContent(), bs);
				r = bs.toByteArray();
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

		return r;
	}

	/***
	 * form 表单请求 ,使用utf-8编码
	 * 
	 * @param urlvalue
	 * @param paras
	 * @return
	 * @author wangzhiyue
	 * @date 2024/06/20 16:12:57
	 */
	public static String post(String urlvalue, Map<String, String> paras) {
		return post(urlvalue, paras, StandardCharsets.UTF_8, CONNECTION_TIME_OUT, SO_TIME_OUT);
	}

	/**
	 * json 请求 ,使用utf-8编码
	 * 
	 * @param urlvalue
	 * @param json
	 * @return
	 * @author wangzhiyue
	 * @date 2024/06/20 16:13:29
	 */
	public static String postJson(String urlvalue, String json) {
		return postJson(urlvalue, json, StandardCharsets.UTF_8, CONNECTION_TIME_OUT, SO_TIME_OUT);
	}

	/**
	 * 上传文件
	 * 
	 * @param url
	 * @param paras
	 * @param charset
	 * @param connectTime
	 * @param timeCout
	 * @param file
	 * @return
	 * @author wangzhiyue
	 * @date 2024/06/20 16:13:50
	 */
	public static String postFile(String url, Map<String, String> paras, Charset charset, int connectTime, int timeCout, File file) {
		String r = "";
		try {
			MultipartEntityBuilder builer = MultipartEntityBuilder.create();
			builer.setCharset(MIME.UTF8_CHARSET);
			HttpPost httpPost = new HttpPost(url);
			builer.setMode(HttpMultipartMode.RFC6532);
			if (paras != null) {
				for (Map.Entry<String, String> e : paras.entrySet()) {
					builer.addTextBody(e.getKey(), e.getValue(), ContentType.TEXT_PLAIN.withCharset(Consts.UTF_8));
				}
			}
			String filetype = file.getName().substring(file.getName().lastIndexOf(".") + 1);
			ContentType contentType = Optional.ofNullable(ContentType.getByMimeType(filetype)).orElse(ContentType.DEFAULT_BINARY.withCharset(Consts.UTF_8));
			builer.addBinaryBody("file", file, contentType, file.getName());
			httpPost.setEntity(builer.build());
			RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTime).setSocketTimeout(timeCout).build();
			httpPost.setConfig(config);
			try (CloseableHttpResponse response = client.execute(httpPost)) {
				HttpEntity entity = response.getEntity();
				r = EntityUtils.toString(entity, charset);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return r;
	}

	/**
	 * 上传文件 使用utf-8变慢
	 * 
	 * @param url
	 * @param paras
	 * @param file
	 * @return
	 * @author wangzhiyue
	 * @date 2024/06/20 16:14:00
	 */
	public static String postFile(String url, Map<String, String> paras, File file) {
		return postFile(url, paras, StandardCharsets.UTF_8, CONNECTION_TIME_OUT, CONNECTION_TIME_OUT, file);
	}

	/**
	 * 上传字节数组文件
	 * 
	 * @param url
	 * @param paras
	 * @param charset
	 * @param connectTime
	 * @param timeCout
	 * @param file
	 * @param fileName
	 * @return
	 * @author wangzhiyue
	 * @date 2024/06/20 16:14:15
	 */
	public static String postFile(String url, Map<String, String> paras, Charset charset, int connectTime, int timeCout, byte[] file, String fileName) {
		String r = "";
		try {
			MultipartEntityBuilder builer = MultipartEntityBuilder.create();
			builer.setCharset(MIME.UTF8_CHARSET);
			HttpPost httpPost = new HttpPost(url);
			builer.setMode(HttpMultipartMode.RFC6532);
			if (paras != null) {
				for (Map.Entry<String, String> e : paras.entrySet()) {
					builer.addTextBody(e.getKey(), e.getValue(), ContentType.TEXT_PLAIN.withCharset(Consts.UTF_8));
				}
			}
			builer.addBinaryBody("file", file, ContentType.DEFAULT_BINARY.withCharset(Consts.UTF_8), fileName);
			httpPost.setEntity(builer.build());
			RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTime).setSocketTimeout(timeCout).build();
			httpPost.setConfig(config);
			try (CloseableHttpResponse response = client.execute(httpPost)) {
				HttpEntity entity = response.getEntity();
				r = EntityUtils.toString(entity, charset);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return r;
	}

	/**
	 * 上传字节数组文件,使用utf-8编码
	 * 
	 * @param url
	 * @param paras
	 * @param file
	 * @param fileName
	 * @return
	 * @author wangzhiyue
	 * @date 2024/06/20 16:14:53
	 */
	public static String postFile(String url, Map<String, String> paras, byte[] file, String fileName) {
		return postFile(url, paras, StandardCharsets.UTF_8, CONNECTION_TIME_OUT, CONNECTION_TIME_OUT, file, fileName);
	}

	public static void main(String[] args) {
		byte[] img = download("https://stplatform.ecej.com/image/bgpicture2.jpg");
		try {
			FileOutputStream out = new FileOutputStream(new File("C:\\Users\\EDY\\Desktop\\work\\1.jpg"));
			IOUtils.write(img, out);
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值