Spring MVC Rest Client获得HttpClientErrorException:404 null

时间:2019-01-06 22:31:26

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

我正在与客户端一起设置Rest Server,并且已经面临几个小时的问题。当我调用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的点。

2 个答案:

答案 0 :(得分:1)

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

只需添加/,您就可以开始使用

答案 1 :(得分:0)

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

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

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