- 功能
- 并发安全,可以多线程使用
- 信任所有证书(内网访问没问题,访问外部链接可能有安全风险)
- 自动释放一段时间不活跃的连接,默认10秒
- 默认每个主机2个连接,最多20个连接
- 代码
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;
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();
}
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;
}
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;
}
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;
}
public static String get(String urlvalue) {
return get(urlvalue, CONNECTION_TIME_OUT, SO_TIME_OUT);
}
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;
}
public static String post(String urlvalue, Map<String, String> paras) {
return post(urlvalue, paras, StandardCharsets.UTF_8, CONNECTION_TIME_OUT, SO_TIME_OUT);
}
public static String postJson(String urlvalue, String json) {
return postJson(urlvalue, json, StandardCharsets.UTF_8, CONNECTION_TIME_OUT, SO_TIME_OUT);
}
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;
}
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);
}
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;
}
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) {
e.printStackTrace();
}
}
}