0

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

应用程序.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
    }
}

分类列表.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;
    }
}

类别.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);

}
4

1 回答 1

0

我猜categoriesProduct和 类型的属性CategoryList。ButCategoryList不是实体,因此您不能通过 URL 直接引用它。为了做到这一点,categories必须是一个List<Category>.

于 2014-09-28T09:11:32.900 回答