工具类
package com.*.utils;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
/**
* @Auther: GXL
* @Date: 2022/10/13/15:48
* @Description: HttpUtil工具类
*/
public class HttpUtil {
protected static Logger logger = LoggerFactory.getLogger(HttpUtil.class);
//字符编码
private static final String charset = "UTF-8";
/**
* @Description: 发送 post 请求,默认字符集为 UTF-8
* @Param: [data, url]
* @return: java.lang.Object
* @Author: GXL
* @Date: 2022/10/13
*/
public static Object sendPost(String data, String url) {
logger.info("【参数:" + data + "】");
StringEntity entity = new StringEntity(data, charset);
HttpClient client = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Content-type", "application/json");
httppost.setEntity(entity);
HttpResponse response = null;
try {
response = client.execute(httppost);
} catch (IOException e) {
e.printStackTrace();
}
HttpEntity resEntity = response.getEntity();
String res = null;
try {
res = EntityUtils.toString(resEntity, charset);
} catch (IOException e) {
e.printStackTrace();
}
logger.info("【返回内容:" + res + "】");
return JSON.parse(res);
}
}
发送请求
public static void main(String[] args) throws RequestException {
List<Map> mapList = new ArrayList<>();
Map map = new HashMap();
map.put("a","b");
mapList.add(map);
Object o = HttpUtil.sendPost(JSON.toJSONString(mapList), "http://192.168.104.121:8083/syncOa/test");
System.out.println(JSON.toJSONString(o));
}
接受请求
@RequestMapping("/test")
@ResponseBody
public void test(@RequestBody List<Map> mapList){
System.out.println("map----------------->"+JSON.toJSONString(mapList));
}