我目前在从另一个 REST 服务调用一个 REST 服务时遇到了一个非常奇怪的问题,我真的可以帮助解决我做错了什么。
首先,了解一下背景:
我有一个 Web 应用程序调用 REST 服务来创建用户帐户(为了便于解释,端点是 localhost:8080/register)。在用户旅程的早期,我调用了一项不同的服务来创建用户的登录凭据 localhost:8090/signup
但我需要在对/register 的调用中检查一些内容,所以在调用中我' m 调用 8090 上的另一个端点以获取此信息 (localhost:8090/availability
)。长话短说,Web 应用程序调用 localhost:8080/register,后者又调用 localhost:8090/availability
。
当我从 REST 客户端或 Web 应用程序本身直接调用可用性端点时,一切都按预期工作,但出于某种奇怪的原因,当我从对注册端点的调用内部调用它时,我得到了一个 HTTP415。任何人都知道出了什么问题吗?
注册 Controller 看起来像这样:
@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;
}
可用性 Controller 看起来像这样:
@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() 中显示的内容实际上是对调用堆栈的多次调用,使用的类与我用来从 webapp 调用服务的类相同(在该上下文),而且我实际上并没有在 isUsernameAvailable 中返回 true(因为那会很愚蠢),但这是复制该问题的代码的最简单版本。
我目前的假设是,我正在做某事,当我看到它时,我会把自己踢过去,但我盯着这段代码看得太久了,以至于无法再看到它。
编辑 Vikdor 下面的评论为我解决了这个问题。我将 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;
}
最佳答案
HTTP415 表示不支持的媒体类型。这意味着 isUsernameAvailable
需要 JSON 格式的输入,但这不是它得到的。
通过执行以下操作,尝试将 Content-Type: application/json
header 显式添加到您的 HTTP 请求中:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
restTemplate.put(uRL, entity);
关于java - Spring MVC - 从另一个休息服务内部调用休息服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34503547/