0

I am trying to create a client for the following URL: 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;
    }
}

And the error being thrown is:

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)

To generate the JSON on the server I use the RepositoryRestResource annotation:

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

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

and

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

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

}
Gaurav Sharma
  • 4,032
  • 14
  • 46
  • 72

1 Answers1

0

I guess categories is a property of Product and of the type CategoryList. But CategoryListis not an entity, so you cannot reference it directly via a URL. In order to do that categories would have to be a List<Category>.

a better oliver
  • 26,330
  • 2
  • 58
  • 66