spring rest service resttemplate postForEntity两个对象

时间:2018-03-13 02:54:10

标签: java spring rest post

我有一个弹簧休息服务,我有一个带有两个参数Product和Catalog的方法。方法是

public void addProductCatalog(Product product,Catalog catalog) {
        logger.info("******** ******** CLIENT: addProductCatalog");


        ResponseEntity response = rest.postForEntity(
            "http://localhost:8080/rest/addProductCatalog", 
            product, null,catalog);

我调用此方法时出现异常

Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 400 null
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:85)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:707)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:660)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:620)
    at org.springframework.web.client.RestTemplate.postForEntity(RestTemplate.java:414)
    at com.abc.rest.client.ProductClient.addProductCatalog(ProductClient.java:34)
    at com.abc.InventoryClientApp.run(InventoryClientApp.java:265)
    at com.abc.InventoryClientApp.main(InventoryClientApp.java:24)

如何在postForEntity中设置两个对象?

1 个答案:

答案 0 :(得分:0)

您的方法调用不正确。创建包含两个对象的常见Pojo。根据需要设置内容类型,然后相应地调用它。

例如。

public class ProductCatalog{
   private Product product;
   private Catalog catalog;

  // getter and setter. 
}

然后按如下方式调用它:

  restTemplate.postForEntity("http://localhost:8080/rest/addProductCatalog", productCatalog, String.class);