网上方案基本都是3种,我的实际应用场景比较简单,所以我选了 HttpClient
主要是将它融入到 Springboot项目里面
一、导入依赖
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.2.1</version>
</dependency>
第二、post请求案例,携带json参数,获取返回结果
public void doPostTestOne() {
// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 创建Post请求
HttpPost httpPost = new HttpPost("http://10.10.123.45:8008/test/add");
//构建post参数
JSONObject postParam= new JSONObject();
postParam.put("content", "参数值");
StringEntity stringEntity = new StringEntity(postParam.toString(), ContentType.APPLICATION_JSON);
httpPost.setEntity(stringEntity);
// 响应模型
CloseableHttpResponse response = null;
try {
// 由客户端执行(发送)Post请求
response = httpClient.execute(httpPost);
// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
System.out.println("响应状态码:" + response.getCode());
if (responseEntity != null) {
System.out.println("响应内容长度为:" + responseEntity.getContentLength());
String strData = EntityUtils.toString(responseEntity);
System.out.println("响应内容"+strData);
//将字符串转成对象,便于取出里面属性的值
JSONObject jsonObject = JSONObject.parseObject(strData);
String data = jsonObject.getString("data");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}