springboot发送request请求的方式
媒介java发送请求的方法有很多,这里只先容两种。
hutool和RestTemplate
下边提供两种后端发送请求的方式,一个是基于hutool工具的,一个是基于RestTemplate的,为什么要写这两种呢,由于有的时间用hutool的方式不太管用,有的时间用RestTemplate也不太管用,所以就且换着用,谁能用,用谁。
hutool方式
get请求
@GetMapping("/userEleList")
@ResponseBody
public JSONObject userEleList(@RequestParam(name = "userCode") String userCode, HttpServletRequest request) {
String Authorization = request.getHeader("Authorization");
String token = request.getHeader("token");
String body = HttpUtil.createGet("http://ip:8068/userEleList?userCode=" + userCode)
.header("Authorization", Authorization)
.header("token", token)
.execute()
.body();
return JSONObject.parseObject(body);
}
@GetMapping("/getKdToken")
@ResponseBody
public JSONObject userEleList(@RequestParam(name = "appId") String appId,
@RequestParam(name = "appSecret") String appSecret,
@RequestParam(name = "grantType") String grantType) {
String post = HttpUtil.get("http://ip:8068/getKdToken?appId=" + appId + "&appSecret=" + appSecret + "&grantType=" + grantType);
return JSONObject.parseObject(post);
}
post请求
@PostMapping("/eleRechargeMoneyAllList")
@ResponseBody
public JSONObject eleRechargeMoneyAllList(@RequestBody Map<String, Object> map, HttpServletRequest request) {
String Authorization = request.getHeader("Authorization");
String token = request.getHeader("token");
Object elemeterId = map.get("elemeterId");
Object money = map.get("money");
Object selOrderno = map.get("selOrderno");
String post = HttpUtil
.createPost("http://ip:8068/eleRechargeMoneyAllList?elemeterId=" + elemeterId + "&money=" + money + "&adds=0&selOrderno=" + selOrderno + "&payType=40")
.header("Authorization", Authorization)
.header("token", token)
.execute()
.body();
return JSONObject.parseObject(post);
}
@PostMapping("/GetClientByCnumber")
@ResponseBody
public JSONObject GetClientByCnumber(@RequestBody Map<String, Object> map) {
String post = HttpUtil.post("http://ip:8006/GetClientByCnumber", map);
return JSONObject.parseObject(post);
}
RestTemplate方式
@PostMapping("/userPricePay")
@ResponseBody
public JSONObject userPricePay(@RequestBody Map<String, Object> map, HttpServletRequest request) {
String sign = request.getHeader("sign");
RestTemplate restTemplate = new RestTemplate();
// 设置请求头,指定Content-Type为application/json
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
headers.set("sign", sign);
// 将解析后的 JSON 对象转换为 MultiValueMap
HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(map, headers);
ResponseEntity<String> exchange = restTemplate.exchange("https://ip:8080/userPricePay", HttpMethod.POST, requestEntity, String.class);
return JSONObject.parseObject(exchange.getBody());
}
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页:
[1]