Spring RestTemplate:GET请求导致400 Bad Request

时间:2014-09-26 05:44:34

标签: java spring resttemplate spring-hateoas

我正在尝试为以下网址创建客户端:http://florist.herokuapp.com/products/1/categories

Application.java

public class Application {

    public static void main(String args[]) {

        RestTemplate restTemplate = new RestTemplate();

        Product product = restTemplate.getForObject(
                "http://florist.herokuapp.com/products/1", Product.class);
        System.out.println("Name: " + product.getName());//works fine

        List<Category> categories = restTemplate.getForObject(
                "http://florist.herokuapp.com/products/1/categories", CategoryList.class).getCategories();//throws error
    }
}

CategoryList.java

@JsonIgnoreProperties(ignoreUnknown = true)
public class CategoryList {

    @JsonProperty("_embedded")
    private List<Category> categories;

    public List<Category> getCategories() {
        return categories;
    }

    public void setCategories(List<Category> categories) {
        this.categories = categories;
    }
}

Category.java

@JsonIgnoreProperties(ignoreUnknown = true)
public class Category {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

抛出的错误是:

Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 400 Bad Request
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)
    at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:598)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:556)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:512)
    at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:243)
    at hello.Application.main(Application.java:17)

要在服务器上生成JSON,我使用RepositoryRestResource注释:

@RepositoryRestResource(collectionResourceRel = "categories", path = "categories")
public interface CategoryRepository extends PagingAndSortingRepository<Category, Long> {

    List<Category> findByName(@Param("name") String name);
}

@RepositoryRestResource(collectionResourceRel = "products", path = "products")
public interface ProductRepository extends PagingAndSortingRepository<Product, Long> {

    List<Product> findByNameIgnoringCase(@Param("name") String name);

}

1 个答案:

答案 0 :(得分:0)

我猜categoriesProductCategoryList类型的属性。但CategoryList不是实体,因此您无法通过URL直接引用它。为此,categories必须是List<Category>