首页 > 解决方案 > 如何将正文添加到具有标头的 SpringBoot RestTemplate Put 请求

问题描述

我的代码使用 restTemplate 来 PUT 请求信息,并使用标头来执行此操作。但是,如何将信息添加到请求的正文中?

在UNIREST中,它会这样做:

 HttpResponse<String> response = Unirest.put(apiUrl + "/photos/" + photo.getId()).headers(standardHeaders()).body("{ \"status\": \"" + status + "\" }").asString();

    if (response.getStatus() != 200) {
        log.error("Status " + response.getStatus() + " returned from CloudCard API when updating photo.");
        return null;
    }

    return new ObjectMapper().readValue(response.getBody(), new TypeReference<Photo>() {
    })

-

我目前拥有的代码如下,我想做与上面对 Unirest 所做的相同的事情,而不是使用 restTemplate。

  public Photo updateStatus(Photo photo, String status) throws Exception {

 RestTemplate restTemplate = new RestTemplate();

         HttpHeaders headers = new HttpHeaders();
         headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
         headers.setContentType(MediaType.APPLICATION_JSON);
         headers.set("X-Auth-Token", accessToken);

    Photo newPhoto = photo;
    newPhoto.setStatus(status);

    ResponseEntity<Photo> response = restTemplate.exchange(apiUrl+ "/photos/" + photo.getId(),
            HttpMethod.PUT,
            new HttpEntity<Photo>(headers),
            new ParameterizedTypeReference<Photo>() {},
           newPhoto);
 return response.getBody();
 }

标签: javaspring-bootgradleresttemplateunirest

解决方案


推荐阅读