目前,我在从一个 REST 服务内部调用另一个 REST 服务时遇到了一个非常奇怪的问题,我真的可以帮忙找出我做错了什么。
首先,了解一些背景:
我有一个 Web 应用程序,它调用 REST 服务来创建用户帐户(为了便于说明,端点是 localhost:8080/register)。在用户旅程的早期,我调用了不同的服务来创建用户的登录凭据localhost:8090/signup
但我需要在 /register 调用中检查一些内容,因此在调用中我调用 8090 上的另一个端点来获取此信息(localhost:8090/availability
)。长话短说,Web 应用程序调用 localhost:8080/register,后者又调用localhost:8090/availability
.
当我从 REST 客户端或 Web 应用程序本身直接调用可用性端点时,一切都按预期工作,但由于某些奇怪的原因,当我从对注册端点的调用内部调用它时,我得到一个 HTTP415。任何人都知道出了什么问题吗?
注册控制器如下所示:
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public UserModel createUser(@RequestBody UserModel userModel) throws InvalidSignupException {
// a load of business logic that validates the user model
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Boolean> response = restTemplate.postForEntity("http://localhost:8090/availability",
userModel.getUsername(), Boolean.class);
System.out.println(response.getBody());
// a load more business logic
return userModel;
}
可用性控制器如下所示:
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public Boolean isUsernameAvailable(@RequestBody String username) {
// a load of business logic that returns a boolean
return Boolean.TRUE;
}
完全公开 - 实际上,我所显示的 createUser() 内容实际上是对调用堆栈的多次调用,使用与我从 web 应用程序调用服务相同的类(在该上下文中运行得很好) ,而且我实际上不只是在 isUsernameAvailable 中返回 true (因为这很愚蠢),但这是复制该问题的代码的最简单版本。
我目前的假设是,我正在做一些当我看到它时我会踢自己的事情,但我已经盯着这段代码太久了,无法再看到它了。
EditVikdor 下面的评论为我解决了这个问题。我将 createUser 方法更改为:
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public UserModel createUser(@RequestBody UserModel userModel) throws InvalidSignupException {
// a load of business logic that validates the user model
RestTemplate restTemplate = new RestTemplate();
restTemplate.setMessageConverters(Arrays.asList(new MappingJackson2HttpMessageConverter()));
ResponseEntity<Boolean> response = restTemplate.postForEntity("http://localhost:8090/availability",
userModel.getUsername(), Boolean.class);
System.out.println(response.getBody());
// a load more business logic
return userModel;
}