【问题标题】:How can I make a Put rest call along with POJO using RestTemplate如何使用 RestTemplate 与 POJO 一起进行 Put rest 调用
【发布时间】:2019-05-26 02:15:53
【问题描述】:

如何使用 RestTemplate 向休息服务发出 PUT 请求,以便我也得到响应。

我必须调用的其余服务是:

@RequestMapping(value = /forgotpassword, method = RequestMethod.PUT, produces = "application/json")
public SuccessResponse resetUserPassword(@RequestBody ResetPasswordDTO resetPasswordDTO) throws GenericException {
    logger.info("--->reset Password");
    return new SuccessResponse(userservice.resetUserPassword(resetPasswordDTO));

}

我需要发送一个 POJO,它也有两个 String 属性。

【问题讨论】:

  • 你有什么视图方法可以展示吗?这只是控制器...

标签: java spring-boot


【解决方案1】:

RestTempalte in (Spring)[https://spring.io/] 的方法 put 没有返回,所以如果你想从服务器获得响应,请尝试使用POST 方法。我修改你的代码如下:

在服务器端:

    @RequestMapping(value = "/forgotpassword", method = RequestMethod.POST, produces = "application/json")
    public ResponseEntity<SuccessResponse> resetUserPassword(@RequestBody ResetPasswordDTO resetPasswordDTO) throws Exception {
        log.info("--->reset Password");
        SuccessResponse response = new SuccessResponse();
        response.setName(resetPasswordDTO.getUsername());
        response.setMessage("success");
        return new ResponseEntity<SuccessResponse>(response, HttpStatus.OK);

    }

在客户端你可以使用 RestTemplate 做一个请求:

ResetPasswordDTO request = new ResetPasswordDTO();
        request.setPasswork("Huawei@123");
        request.setUsername("c00382802");
        ResponseEntity<SuccessResponse> response =template.postForEntity("http://localhost:8080//forgotpassword",request,SuccessResponse.class);
        System.out.println(response.getBody().toString());

您可以从(春季)获得更多信息[https://spring.io/]

【讨论】:

  • 服务器端代码已经在运行,我们无法更改它。从客户端必须只使用 PUT 请求。
【解决方案2】:

对于PUT 使用RestTemplate.exchange() 方法

示例

 MyJaxbRequestDataObjectrequest = createMyJaxbRequestDataObject();
    Map<String, String> uriArguments= createUriArguments();
    String url = restBaseUrl + "/myputservice/{usertId}?servicekey={servicekey}";

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_XML);
    HttpEntity<MyJaxbRequestDataObject> entity = new HttpEntity<MyJaxbRequestDataObject>(request, headers);
    ResponseEntity<MyJaxbResponseDataObject> responseWrapper = shogunRestTemplate.exchange(url, HttpMethod.PUT, entity, MyJaxbResponseDataObject.class, uriArguments);
    MyJaxbResponseDataObjectresponse = responseWrapper.getBody();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-06
    • 1970-01-01
    相关资源
    最近更新 更多