public class HttpClientUtil {
private static final Logger LOG = LoggerFactory.getLogger(HttpClientUtil.class);
private final static HttpClientUtil httpClientUtil = new HttpClientUtil();
private HttpClientUtil(){}
public static HttpClientUtil getInstance() {return httpClientUtil;}
public String httpGet(String url) throws IOException {
CloseableHttpClient httpClient = createDefault();
CloseableHttpResponse httpResponse = httpClient.execute(new HttpGet(url));
return getStringResponse(httpResponse);
}
public String httpGet(String url, Map
CloseableHttpClient httpClient = createDefault();
URIBuilder urlBuilder = new URIBuilder(url);
if (param != null && !param.isEmpty()) {
for(Map.Entry
urlBuilder.setParameter(entry.getKey(), entry.getValue());
}
}
CloseableHttpResponse httpResponse = httpClient.execute(new HttpGet(urlBuilder.build()));
return getStringResponse(httpResponse);
}
public
return getTResponse(httpGet(url), returnClass);
}
public
return getTResponse(httpGet(url, param), returnClass);
}
public
CloseableHttpClient httpClient = createDefault();
HttpPost httpPost = new HttpPost(url);
if (param != null) {
ObjectMapper mapper = new ObjectMapper();
try {
StringEntity s = new StringEntity(mapper.writeValueAsString(param));
s.setContentEncoding("UTF-8");
s.setContentType("application/json");//发送json数据需要设置contentType
httpPost.setEntity(s);
} catch (JsonProcessingException e) {
LOG.error("ObjectMapper writeValueAsString error.", e);
}
}
return getStringResponse(httpClient.execute(httpPost));
}
public
return getTResponse(httpPost(url, param, paramClass), returnClass);
}
protected CloseableHttpClient createDefault() {return HttpClientBuilder.create().build();}
protected String getStringResponse(CloseableHttpResponse httpResponse) throws IOException {
HttpEntity httpEntity = httpResponse.getEntity();
return httpEntity == null ? null : EntityUtils.toString(httpEntity);
}
private
if (httpResponse == null || httpResponse.length() == 0) return null;
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(httpResponse, returnClass);
}