我现在有一个非常奇怪的问题,从另一个内部调用一个REST服务,我真的可以用手来解决我做错了什么.
首先,有点背景:
我有一个webapp,它调用REST服务来创建一个用户帐户(为了解释这个,端点是localhost:8080 / register).在用户旅程的早期,我调用了一个不同的服务来创建用户的登录凭证localhost:8090 / signup但是我需要检查调用/ register中的一些内容,以便在调用内部我呼叫到另一个端点在8090获取此信息(localhost:8090 / availability).简而言之,webapp调用localhost:8080 / register,然后调用localhost:8090 / availability.
当我直接从REST客户端或webapp本身调用可用性端点时,一切都按预期工作,但由于某些奇怪的原因,当我从调用寄存器端点的内部调用它时,我得到一个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()的内容显示的实际上是几次调用调用堆栈,使用与我用来从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格式输入,但这不是它所获得的.
尝试通过执行以下操作向您的HTTP请求显式添加Content-Type:application / json标头:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
restTemplate.put(uRL, entity);