springboot中使用restTemplate发送带参数和请求头的post,get请求
最近在工作中使用到了用restTemplate去获取网站数据填入到数据库中,在这里记录下来以便以后使用:
代码很简单,一些注解我也写在了代码中
@RequestMapping("/test") @ResponseBody public void test() { try { RestTemplate restTemplate = new RestTemplate(); URI uri = new URI("http://vs.clouddkj.com/YDS/doPost"); HttpHeaders headers = new HttpHeaders(); headers.add("Cookie", "ASP.NET_SessionId=vr2d21dftdzblg5edxlp1ytn"); //添加参数,因为HttpEntity里面的参数是MultiValueMap类型的,所以使用这个map集合 MultiValueMap<String, String> map = new LinkedMultiValueMap<>(); map.add("className", "CloudDot.DC.BLL.DCBLL"); map.add("methodName", "QueryDataLibList"); map.add("params", "[\"\"]"); //添加请求的实体类,这里第一个参数是要发送的参数,第二个参数是请求头里的数据 HttpEntity<Object> requestEntity = new HttpEntity<>(map, headers); //跟下面使用交换机的方法结果一样 /*String s = restTemplate.postForObject(uri, requestEntity, String.class); JSONObject json = JSON.parseObject(s); System.out.println(json);*/ ResponseEntity<String> exchange = restTemplate.exchange(uri, HttpMethod.POST, requestEntity, String.class); JSONObject jsonObject = JSON.parseObject(exchange.getBody()); System.out.println(jsonObject); List<Map<String, String>> resultList = (List<Map<String, String>>) jsonObject.get("Result");for (Map<String, String> obj : resultList) { System.out.println(obj); //在这里把你获取到的数据封装到你需要的实体类中,调用你需要的方法即可存入数据库 } } catch (URISyntaxException e) { e.printStackTrace(); } }
这里有些人可能就有些疑问,为什么参数是要用
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
这种map集合,因为在
HttpEntity<Object> requestEntity = new HttpEntity<Object>(map, headers);
这里面使用的参数类型就是以上map,源码为证:不管你调用的是哪种构造方法,到最后都是调用第四种构造方法,参数就是MultiValueMap类型。
亲测HashMap不行!!!
protected HttpEntity() { this((Object)null, (MultiValueMap)null); } public HttpEntity(T body) { this(body, (MultiValueMap)null); } public HttpEntity(MultiValueMap<String, String> headers) { this((Object)null, headers); } public HttpEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers) { this.body = body; HttpHeaders tempHeaders = new HttpHeaders(); if (headers != null) { tempHeaders.putAll(headers); } this.headers = HttpHeaders.readOnlyHttpHeaders(tempHeaders); }
这里再多说一下MultiValueMap这个接口,是一个键对应多个值,value是一个list集合,Spring的内部实现是LinkedMultiValueMap;
LinkedMultiValueMap默认是按照你插入的顺序进行排序。
public interface MultiValueMap<K, V> extends Map<K, List<V>> { @Nullable V getFirst(K var1); void add(K var1, @Nullable V var2); void addAll(K var1, List<? extends V> var2); void addAll(MultiValueMap<K, V> var1); void set(K var1, @Nullable V var2); void setAll(Map<K, V> var1); Map<K, V> toSingleValueMap(); }
相关推荐
似水流年梦 2020-08-09
牧场SZShepherd 2020-05-27
pengGeiii 2020-05-11
cas的无名 2020-04-26
tinydu 2020-03-01
yungame 2020-02-23
tinydu 2020-02-18
xiaonao00 2020-01-17
sdaq 2020-01-09
SHIL 2019-12-14
gongruitao 2019-12-14
yungame 2019-11-11
yungame 2019-11-06
hell0kitty 2019-10-26
zhujiangtaotaise 2019-10-26
畅聊架构 2019-10-20
carpediemvv 2019-07-01
hehehechen 2019-06-30