1.引入所需要的jar包
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
2.编写工具类(JSON格式)
package com.springmvc.util;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class HttpPostUtil {
public static String doPost(String url, String bodyJson){
//创建CloseableHttpClient对象
CloseableHttpClient client = HttpClients.createDefault();
//创建HttpPost对象
HttpPost httpPost = new HttpPost(url);
//设置请求参数
httpPost.setEntity(new StringEntity(bodyJson, "utf-8"));
//调用CloseableHttpClient对象的execute(),发送请求
CloseableHttpResponse response = null;
String result = "";
try {
response = client.execute(httpPost);
//调用CloseableHttpResponse对象的getEntity(),获得HttpEntity对象,该对象包装了服务器的响应内容
HttpEntity entity = response.getEntity();
//获取返回的参数
result = EntityUtils.toString(entity);
return result;
}catch (Exception e){
System.out.println("发送post失败");
}finally {
if (client != null){
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (response != null){
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
}