[英]Not getting my response when calling my api using MVVM and Retrofit?
[英]Why is my controller calling different API when there is no match API for the request?
我正在开发一个 Spring 启动项目,它会产生奇怪的行为,例如:
我有两个 API 如下
Controller 文件
@GetMapping("/list/employees")
public ResponseEntity<List<Employee>> getEmployees(){
List<Employee> list = employeeService.getAllEmployees();
return new ResponseEntity<List<Employee>>(list, new HttpHeaders(), HttpStatus.OK );
}
@GetMapping("employee/{id}")
public ResponseEntity<Employee> getEmployeeById(@PathVariable("id") long id) throws RuntimeException{
Employee employee = employeeService.getEmployee(id);
return new ResponseEntity<Employee>(employee,new HttpHeaders(),HttpStatus.OK);
}
服务文件
/* return all employees */
public List<Employee> getAllEmployees(){
List<Employee> listEmployee = employeeRepo.findAll();
if(listEmployee.size()>0){
return listEmployee;
}else{
return new ArrayList<Employee>();
}
}
/*
RETURN SINGLE EMPLOYEE BY ID
*/
public Employee getEmployee(long id) throws RuntimeException{
Optional<Employee> employee = employeeRepo.findById(id);
if(employee.isPresent()){
return employee.get();
}else{
new RuntimeException("Record not found");
}
return null;
}
但是在Postman中运行它们会给出奇怪的 output,例如:
第二个 API 返回单身员工的正确行为
http://127.0.0.1:8080/employee/3
{
"id": 3,
"firstName": "Caption",
"lastName": "America",
"email": "cap@marvel.com"
}
同一个 API 的行为不正确(我这次输入了错误的路径)
http://127.0.0.1:8080/employees/3
API 路径错误(员工/3)
{
"firstName": "Caption",
"lastName": "America",
"email": "cap@marvel.com",
"_links": {
"self": {
"href": "http://127.0.0.1:8080/employees/3"
},
"employee": {
"href": "http://127.0.0.1:8080/employees/3"
}
}
}
与根 URI 的行为相同,我没有使用主 URI 触发任何操作,但仍然像上面的 API 一样给出 output。
这些不需要的 API 调用的原因是什么?
看起来您的 class 路径上有 Spring 数据 Rest 。 它将根据存储库自动连接路径。 第二个响应是 HATEOAS 响应。
一个简单的测试是检查 maven/gradle。 如果您看到 spring-data-rest,请将其注释掉并重试。
没有不需要的 API 调用。 这就是 HATEOS 响应的表示方式,如文档中所述:
超媒体的基本思想是用超媒体元素丰富资源的表示。 最简单的形式是链接。 它们指示客户端可以导航到某个资源。 相关资源的语义在所谓的链接关系中定义。
如上所述,尝试查找 spring 引导 hateos 依赖项并注释或删除它,然后它应该恢复正常 REST JSON 响应。
如果您使用的是 maven,请查找:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
如果您使用的是 gradle,请查找:
implementation 'org.springframework.boot:spring-boot-starter-hateoas'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.