添加依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
以json格式参数发送post请求
public static String sendJsonPost(String url, Map<String, String> headerMap, JSONObject jsonObject) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
if (headerMap != null) {
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
post.setHeader(entry.getKey(), entry.getValue());
}
}
CloseableHttpResponse response = null;
try {
StringEntity s = new StringEntity(jsonObject.toString());
s.setContentType("application/json");
s.setContentEncoding("UTF-8");
post.setEntity(s);
response = httpClient.execute(post);
System.out.println(response);
if(response != null) {
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity, "UTF-8");
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
httpClient.close();
if(response != null) response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
以userId=333&name=777的字符串参数发送post请求
public static String sendStringPost(String url, Map<String, String> headerMap, String param) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
if (headerMap != null) {
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
post.setHeader(entry.getKey(), entry.getValue());
}
}
CloseableHttpResponse response = null;
try {
post.setEntity(new StringEntity(param,"UTF-8"));
response = httpClient.execute(post);
if(response != null) {
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity, "UTF-8");
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
httpClient.close();
if(response != null) response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}