[java]代码库
//依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.6</version>
</dependency>
public static String httpPost(String url, Map<String, Object> param) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
HttpEntity entity = null;
try {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
ContentType jsonType = ContentType.create("text/json", Charset.forName("utf-8"));
for ( String key : param.keySet() ) {
builder.addTextBody(key, JSON.toJSONString( param.get(key) ), jsonType);
}
entity = builder.setCharset(CharsetUtils.get("utf-8")).setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.build();
httpPost.setEntity(entity);
// 执行发送请求,并获取返回值
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;
}