首页 > 解决方案 > 无法通过 RestTemplate PUT 请求发送 Pojo

问题描述

无法通过 RestTemplate PUT 请求发送 Pojo。

我有一项需要从其他应用程序调用的休息服务。服务是:

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

}

我正在使用 RestTemplate 调用上述服务,为此我需要发送一个 POJO 以及 PUT 请求。使用 RestTemplate 的代码是:

public ResponseEntity<SuccessResponse> resetUserPassword(ResetPasswordDTO resetPasswordDTO)
        throws ServiceGenericException {
    ResponseEntity<SuccessResponse> ssoUserResponse = null;
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<ResetPasswordDTO> requestEntity = new HttpEntity<ResetPasswordDTO>(resetPasswordDTO,headers);

    ssoUserResponse = restTemplate.exchange("http://localhost:5858/api/unsecured/resetpassword", HttpMethod.PUT, requestEntity,
            SuccessResponse.class);
    return ssoUserResponse;
}

我无法拨打电话。我遇到以下异常:org.springframework.web.client.HttpClientErrorException: 400 null。

我要发送的 POJO:

public class ResetPasswordDTO implements Serializable {

private static final long serialVersionUID = -2372400429023166735L;
private String password;
private String activationCode;
}

标签: javaspring-boot

解决方案


Spring 无法将您的 json 解析为 POJO,因为变量声明为私有并且您没有任何 getter/setter。您需要将它们公开或将 getter/setter 添加到您的 ResetPasswordDTO 类。

另外,我强烈建议你看看 Lombok,它让这样的事情变得非常容易。


推荐阅读