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