本文使用HttpClient包实现了HTTP的post和get请求。
· POST
public static String httpPost(String url, String body, Map<String, String> headers) throws Exception {
CloseableHttpClient client = HttpClients.createDefault();
String strResult = null;
HttpPost method = new HttpPost(url);
if (null != body) {
StringEntity entity = new StringEntity(body, "UTF-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
method.setEntity(entity);
}
if (null != headers) {
headers.forEach((k, v) -> method.addHeader(k, v));
}
HttpResponse result = client.execute(method);
url = URLDecoder.decode(url, "UTF-8");
if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
strResult = EntityUtils.toString(result.getEntity());
}
return strResult;
}
· GET
public static String httpGet(String url, Map<String, String> headers) throws Exception {
String strResult = null;
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet(url);
if (null != headers) {
headers.forEach((k, v) -> request.addHeader(k, v));
}
HttpResponse response = client.execute(request);
url = URLDecoder.decode(url, "UTF-8");
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
strResult = EntityUtils.toString(response.getEntity());
}
return strResult;
}