1、pom文件添加相关依赖包
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
</dependency>
2、编写工具类代码
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
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;
public class HttpClientUtil {
/**
* post请求(用于请求json格式的参数)
* @param url 接口地址
* @param params 接口参数
* @return
*/
public static String doPost(String url, String params) {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);// 创建httpPost
httpPost.setHeader("Accept", "application/json"); //接收报文类型
httpPost.setHeader("Content-Type", "application/json"); //发送报文类型
if(params != null && !"".equals(params)){
StringEntity entity = new StringEntity(params, "GBK");
httpPost.setEntity(entity);
}
CloseableHttpResponse response = null;
try {
response = httpclient.execute(httpPost);
StatusLine status = response.getStatusLine();
int state = status.getStatusCode();
if (state == HttpStatus.SC_OK) {
HttpEntity responseEntity = response.getEntity();
String jsonString = EntityUtils.toString(responseEntity,"GBK");
return jsonString;
}
else{
System.out.println(state);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (response != null)response.close();
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}