【问题标题】:Spring MVC Rest Client getting HttpClientErrorException: 404 nullSpring MVC Rest Client 获取 HttpClientErrorException: 404 null
【发布时间】:2019-06-01 15:42:42
【问题描述】:

我正在与客户端一起设置一个 Rest 服务器,但我已经面临几个小时的问题。当我调用 getPoints() 方法时一切正常,但是当我调用 getPoint(Long id)、deletePoint(Long id) 和 postPoint() 时,我得到:线程“main”中的异常 org.springframework.web.client.HttpClientErrorException : 404 为空。

客户端:

public List<Point> getPoints()
{
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<List<Point>> pointResponse = restTemplate.exchange("http://localhost:5000/points", HttpMethod.GET, null,
            new ParameterizedTypeReference<List<Point>>()
            {});
    List<Point> points = pointResponse.getBody();
    return (points);
}

public Point getPoint(long id)
{
    RestTemplate restTemplate = new RestTemplate();
    Point point = restTemplate.getForObject("http://localhost:5000/points" + id, Point.class);
    return point;
}

public void postPoint()
{
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.postForObject("http://localhost:5000/points", this, this.getClass());
}

public void deletePoint(Long id)
{
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.delete("http://localhost:5000/points" + id);
}

服务器端:

public class PointsController {

private final PointsRepository repository;

PointsController(PointsRepository repository){
    this.repository=repository;
}

@GetMapping("/points/")
List<Points> all() {
    return repository.findAll();
}

@PostMapping("/points/")
Points newPoints(@RequestBody Points newPoints){
    return repository.save(newPoints);
}

@GetMapping(value = "/points/{id}/", produces = "application/json; charset=UTF-8")
Resource<Points> one(@PathVariable Long id) {
    Points point = repository.findById(id).orElseThrow(() -> new PointsNotFoundException(id));

    return new Resource<>(point,
            linkTo(methodOn(PointsController.class).one(id)).withSelfRel(),
            linkTo(methodOn(PointsController.class).all()).withRel("points"));
}

@DeleteMapping("/points/{id}/")
void deletePoints(@PathVariable Long id) {
    repository.deleteById(id);
}

}

什么会导致问题?当我输入浏览器地址时:http://localhost:5000/points/1 我通常会得到 id 1 的点。

【问题讨论】:

  • 我不想把这个放在答案中,但是你错过了尾随的/
  • 谢谢,但这并不能解决问题
  • 您在服务器端而不是在客户端添加了/?请看我的回答

标签: java spring model-view-controller http-status-code-404


【解决方案1】:

您在getPost() 方法中合并的字符串将是:http://localhost:5000/points1 而不是http://localhost:5000/points/1

只需添加/就可以了

【讨论】:

  • 感谢 GetMapping 和 DeleteMapping 的帮助,PostMapping 仍然无法正常工作,但我的代码可能有问题。
【解决方案2】:

我不确定,但您可以尝试以下操作:

public void postPoint()
{
  RestTemplate restTemplate = new RestTemplate();
  restTemplate.postForObject("http://localhost:5000/points/", this, this.getClass());
}

因为我在服务器端看到了post映射:@PostMapping("/points/")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-23
    • 1970-01-01
    • 1970-01-01
    • 2019-03-10
    • 2015-04-24
    • 1970-01-01
    • 2019-07-26
    相关资源
    最近更新 更多