restTemplate發送get請求攜帶header


 

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM