簡體   English   中英

Spring RestTemplate:GET請求導致400錯誤請求

[英]Spring RestTemplate: GET request causes 400 Bad Request

我正在嘗試為以下URL創建客戶端: http : //florist.herokuapp.com/products/1/categories

應用程序

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);

}

我猜categoriesProduct的屬性,類型是CategoryList 但是CategoryList不是實體,因此您不能直接通過URL引用它。 為了做到這一點, categories必須是List<Category>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM