springboot整合httpclient有参请求表单和json

1.依赖

<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
二.Controller
post json 传参

/**
* post json传参
* @param param
* @return
* @throws IOException
*/
@RequestMapping("aa")
public String Test(@RequestBody Map<String, String> param) throws IOException {

//构建一个httpclient请求
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
try {
//创建一个post请求
HttpPost httpPost = new HttpPost("http://localhost:9910/hxdevice/device/list");
//post请求传入json数据
StringEntity se = new StringEntity(JSON.toJSONString(param), "utf-8");
//设置请求的时候为application/json
se.setContentType("application/json");
//放入httppost中
httpPost.setEntity(se);
//调用请求方法
response = httpClient.execute(httpPost);
//判断返回结果
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
JSONObject jsonObject = JSONObject.parseObject(content);
System.out.println(jsonObject);
}
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}

return "成功";
}
post表单传参
/**
* 表单传参
* @param param
* @return
* @throws IOException
*/

@RequestMapping("bb")
public String bb(@RequestBody Map<String, String> param) throws IOException {

//构建一个httpclient请求
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
UrlEncodedFormEntity formEntity;
try {
//创建一个post请求
HttpPost httpPost = new HttpPost("http://localhost:8080/test/qwe");
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : param.entrySet()) {
parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
//post请求传入json数据
formEntity = new UrlEncodedFormEntity(parameters,"UTF-8");
//放入httppost中
httpPost.setEntity(formEntity);
//调用请求方法
response = httpClient.execute(httpPost);
//判断返回结果
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(content);
}
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}

return "成功";
}

 
posted @ 2021-06-10 13:47  liberalartsy  阅读(596)  评论(0)    收藏  举报