//依赖 |
<dependency> |
<groupId>org.apache.httpcomponents</groupId> |
<artifactId>httpmime</artifactId> |
<version> 4.5 . 6 </version> |
</dependency> |
public static String httpPost(String url, String contentType, Map<String, String> param) { |
CloseableHttpClient httpClient = HttpClients.createDefault(); |
HttpPost httpPost = new HttpPost(url); |
try { |
httpPost.setHeader( "Content-Type" , contentType); |
List<NameValuePair> list = new ArrayList<>(); |
for (String key : param.keySet()) { |
list.add( new NameValuePair() { |
@Override |
public String getName() { |
return key; |
} |
@Override |
public String getValue() { |
return param.get(key); |
} |
}); |
} |
httpPost.setEntity( new UrlEncodedFormEntity(list, StandardCharsets.UTF_8)); |
// 执行发送请求,并获取返回值 |
CloseableHttpResponse response = httpClient.execute(httpPost); |
HttpEntity entity2 = response.getEntity(); |
String result = "" ; |
if (entity2 != null ) { |
result = EntityUtils.toString(entity2, Charset.defaultCharset()); |
System.out.println( "response_length: " + entity2.getContentLength()); |
System.out.println( "response: " + result); |
} |
return result; |
} catch (IOException e) { |
e.printStackTrace(); |
} |
return null ; |
} |