1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
| package com.example.demo.utils;
import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.http.Header; import org.apache.http.HttpHeaders; 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.*; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects;
public class HttpClientUtil {
private static final Logger log = LoggerFactory.getLogger(HttpClientUtil.class);
private static final CloseableHttpClient HTTP_CLIENT;
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private static final int TIMEOUT = 10 * 1000;
static { RequestConfig clientConfig = RequestConfig.custom() .setConnectTimeout(TIMEOUT) .setSocketTimeout(TIMEOUT) .setConnectionRequestTimeout(TIMEOUT) .build();
List<Header> headers = new ArrayList<>(); headers.add(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json")); HTTP_CLIENT = HttpClientBuilder.create() .setDefaultRequestConfig(clientConfig) .setDefaultHeaders(headers) .build();
Runtime.getRuntime().addShutdownHook(new Thread(() -> { if (null != HTTP_CLIENT) { try { HTTP_CLIENT.close(); log.info("close http client success."); } catch (IOException e) { log.error("close http client error.", e); } } })); }
public static HttpResult doGet(String url, Map<String, Object> map) throws Exception {
URIBuilder uriBuilder = new URIBuilder(url);
if (map != null){ for (Map.Entry<String, Object> entry : map.entrySet()){ uriBuilder.setParameter(entry.getKey(), entry.getValue().toString()); } }
HttpGet httpGet = new HttpGet(uriBuilder.build());
return execute(httpGet); }
public static HttpResult doGet(String url) throws Exception { return doGet(url, null); }
public static HttpResult doPost(String url, Map<String, Object> reqMap, Map<String, String> headersMap) throws Exception {
HttpPost httpPost = new HttpPost(url); for (Map.Entry<String, String> entry : headersMap.entrySet()) { httpPost.addHeader(entry.getKey(), entry.getValue()); }
if (reqMap != null) {
StringEntity formEntity = new StringEntity(OBJECT_MAPPER.writeValueAsString(reqMap), StandardCharsets.UTF_8.name());
httpPost.setEntity(formEntity); }
return execute(httpPost); }
public static HttpResult doPostJson(String url, String json) throws IOException {
HttpPost httpPost = new HttpPost(url); StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON); httpPost.setEntity(entity); return execute(httpPost); }
public static HttpResult doPost(String url) throws Exception { return doPost(url, null, null); }
public static HttpResult doPut(String url, Map<String, Object> map) throws Exception {
HttpPut httpPut = new HttpPut(url);
if (map != null) { List<NameValuePair> params = new ArrayList<>();
for (Map.Entry<String, Object> entry : map.entrySet()) { params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString())); }
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8.name());
httpPut.setEntity(formEntity); }
return execute(httpPut); }
public static HttpResult doDelete(String url, Map<String, Object> map) throws Exception {
URIBuilder uriBuilder = new URIBuilder(url);
if (map != null) { for (Map.Entry<String, Object> entry : map.entrySet()) { uriBuilder.setParameter(entry.getKey(), entry.getValue().toString()); } }
HttpDelete httpDelete = new HttpDelete(uriBuilder.build());
return execute(httpDelete); }
private static HttpResult execute(HttpRequestBase httpRequest) throws IOException { CloseableHttpResponse response = null; try { response = HTTP_CLIENT.execute(httpRequest); if (Objects.nonNull(response) && Objects.nonNull(response.getStatusLine())) { String content = ""; if (Objects.nonNull(response.getEntity())) { content = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8.name()); } return new HttpResult(response.getStatusLine().getStatusCode(), content); } return new HttpResult(HttpStatus.SC_INTERNAL_SERVER_ERROR); } finally { release(response); } }
public static void release(CloseableHttpResponse httpResponse) throws IOException { if (httpResponse != null) { httpResponse.close(); } } }
|