restTemplate發送POST請求時可以通過restTemplate.postForObject(url.toString(),requestEntity,String.class) 方式請求,但是GET卻沒有相應的方法,但是可以使用exchange替代,代碼如下: HttpHeaders headers = new HttpHeaders(); headers.add("token",token); HttpEntity<String> requestEntity = new HttpEntity<>(null, headers); ResponseEntity<String> resEntity = restTemplate.exchange(url.toString(), HttpMethod.GET, requestEntity, String.class);
@ApiModel public class CommonResult<T> { @ApiModelProperty(value = "狀態碼") private Integer code; @ApiModelProperty(value = "信息") private String msg; private T data; public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public T getData() { return data; } public void setData(T data) { this.data = data; } @Override public String toString() { return "CommonResult{" + "code=" + code + ", msg='" + msg + '\'' + ", data=" + data + '}'; } }
HttpHeaders headers = new HttpHeaders(); headers.add("app_key","82328899643506666"); HttpEntity<String> requestEntity = new HttpEntity<>(null, headers); String urlTemplate = "http://localhost/test?id=%s&type_id=%s"; String url = String.format(urlTemplate,1,2); ResponseEntity<CommonResult> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, CommonResult.class); if (HttpStatus.OK == responseEntity.getStatusCode()) { CommonResult commonResult = responseEntity.getBody(); if (ResultCode.SUCCESS == commonResult.getCode()) { return commonResult; } else { log.error("#method# 遠程調用失敗 code = [{}], msg = [{}]", commonResult.getCode(), commonResult.getMsg()); } } else { log.error("#method# 遠程調用失敗 httpCode = [{}]", responseEntity.getStatusCode()); }
————————————————
版權聲明:本文為CSDN博主「0-18-0」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_26702601/java/article/details/91864118