Spring Rest模板 - 删除错误请求的操作失败

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (7)

我正在使用Spring Rest模板执行删除操作。

我收到400 Bad Request。但是同样的要求正在与Postman合作。网址:http:// localhost:8080 / product-service / customer / 123456 / customer-items / US?productCode = A-124896

控制器代码:

     @DeleteMapping(value = "/customer/{customer-number}/customer-items/{country}", params = {"uline-item-number"} , produces = {"application/json"})

public ResponseEntity<Boolean> deleteCustomerItem( @PathVariable("customer-number") final String customerNumber, 
               @PathVariable("country") final String countryCode,
                @RequestParam("productCode") final String productCode) {
            try {
                return new ResponseEntity<>(appCustomerService.deleteCustomerItem(customerNumber, countryCode, productCode), HttpStatus.OK);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
            }
        }

服务Impl:

public Boolean deleteCustomerItem(String customerNumber, String countryCode, String productCode)
            throws Exception{
        Map<String, String> uriVariables = new HashMap<>();
        uriVariables.put("productCode", productCode);
        String productUrl = http://localhost:8080/product-service/customer/123456/customer-items/US";
        try {
            restTemplate.exchange(productUrl , HttpMethod.DELETE, HttpEntity.EMPTY, Void.class, uriVariables);
            return true;
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }

我在请求中遗漏了什么吗?请帮我解决这个问题。

提问于
用户回答回答于

你弄乱路径参数和查询参数。以下应该正常工作:

    String url = "http://localhost:8080/product-service/customer/{customer-number}/customer-items/{country}";

    // Path parameters should be here
    Map<String, String> uriParams = new HashMap<>();
    uriParams.put("customer-number", "123456");
    uriParams.put("country", "US");

    URI productUri = UriComponentsBuilder.fromUriString(url)            
            .queryParam("productCode", productCode) // query parameters should be here
            .buildAndExpand(uriParams)
            .toUri();

    restTemplate.exchange(productUri, HttpMethod.DELETE, HttpEntity.EMPTY, Void.class);

扫码关注云+社区

领取腾讯云代金券