Rob*_*Rob 5 java rest spring spring-mvc microservices
从另一个内部调用一个REST服务,我目前遇到一个非常奇怪的问题,我真的可以帮忙弄清楚我在做什么错。
所以首先,有一点上下文:
我有一个webapp可以调用REST服务来创建用户帐户(为了便于说明,端点为localhost:8080 / register)。在用户旅程的早期,我调用了另一项服务来创建用户的登录凭据,localhost:8090/signup
但是我需要检查对/ register的调用中的一些内容,因此在调用过程中,我要向8090上的另一个端点进行调用以获取此信息信息(localhost:8090/availability
)。长话短说,Web应用程序会调用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;
}
Run Code Online (Sandbox Code Playgroud)
可用性控制器如下所示:
@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;
}
Run Code Online (Sandbox Code Playgroud)
全面披露-实际上,我显示为createUser()的内容实际上是调用堆栈上的多次调用,使用的类与我从Web应用程序调用服务时使用的类相同(在那种情况下效果很好) ,而我实际上并没有在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;
}
Run Code Online (Sandbox Code Playgroud)
HTTP415表示不支持的媒体类型。这意味着isUsernameAvailable
需要 JSON 格式的输入,但这并不是它得到的。
尝试Content-Type: application/json
通过执行以下操作向 HTTP 请求显式添加标头:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
restTemplate.put(uRL, entity);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
28435 次 |
最近记录: |