无法通过RestTemplate PUT请求发送Pojo

时间:2018-12-28 06:10:30

标签: java spring-boot

无法通过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空。

我要发送的POJO:

public class ResetPasswordDTO implements Serializable {

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

2 个答案:

答案 0 :(得分:1)

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

此外,我强烈建议您看Lombok,它使这样的操作非常容易。

答案 1 :(得分:0)

收到4xx错误时,抛出

HttpClientErrorException。因此,如果发送的请求在设置标头或发送错误的数据时出错,则可能会收到此异常。您应该检查您的请求,并在调用API时验证从您方发送的POJO的详细信息。

如果您仍然无法查明问题,请分享您的POJO,请求详细信息和完整的堆栈跟踪。

有关HTTP 400错误代码的更多详细信息,您可以参考400 BAD request HTTP error code meaning?