优雅的发送http请求
做项目的时候,请求第三方接口是常用的功能:
一、get常用的方法及传参
1、使用占位符:适用于参数已知
String url = "https://q.stock.sohu.com/hisHq?code={code}8&start={start}&end={end}&stat={stat}&order={order}&period={period}&callback={callback}&rt={rt}";
Map<String, Object> params = new HashMap<>();
params.put("code", "cn_601398");
params.put("start", "20231130");
params.put("end", "20231230");
params.put("stat", 1);
params.put("order", "D");
params.put("period", "d");
params.put("callback", "historySearchHandler");
params.put("rt", "json");
ResponseEntity<RestVO> forEntity = restTemplate.getForEntity(url, RestVO.class, params);
2、使用UriComponentsBuilder和LinkedMultiValueMap:适用于参数个数不定
MultiValueMap<String, String> params = new LinkedMultiValueMap(); String starttime = i + startTime[j]; String endtime = i + endTime[j]; params.add("code", "cn_" + 601398); params.add("start", starttime); params.add("end", endtime); params.add("stat", "1"); params.add("order", "D"); params.add("period", "d"); params.add("callback", "historySearchHandler"); params.add("rt", "json"); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url); URI uri = builder.queryParams(params).build().encode().toUri();
ResponseEntity<RestVO> forEntity= restTemplate.getForEntity(uri, RestVO.class);
拼接结果都一样:https://q.stock.sohu.com/hisHq?code=cn_601398&start=20231130&end=20231230&stat=1&order=D&period=d&callback=historySearchHandler&rt=json