【问题标题】:org.springframework.web.client.HttpClientErrorException: 400 Bad Request for PUTorg.springframework.web.client.HttpClientErrorException: 400 Bad Request for PUT
【发布时间】:2019-12-30 20:08:08
【问题描述】:

我一直在尝试使用restTemplate 使用带有PUT 动词的API。我有以下代码

 RestTemplate restTemplate = new RestTemplate();
 HttpHeaders headers = new HttpHeaders();
 headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
 HttpEntity<String> entity = new HttpEntity<String>(jsonString,headers);
 restTemplate.put(Url+"/'"+id,entity, String.class);

我的jsonString有以下内容。

{ 
 "id":"asdfafaff-fsf3-4b1c-a7c4-13352252daa",
 "product":"MyProductName",
 "Organization":"my company name test",
 "Organizationid":"tert122Teq-rtq-q556trt-qtqtqt3-131rtqtqt",
 "ProductProperties":"Hc2",
 "Locations":{ 
   "results":[ 

    ]
 },
 "Status":"Gone",
 "DisabledByType":null,
 "roles":null,
 "Url":"wwww.google.com",
 "Key":"xxxxxxxxxx",
 "Secret":"xxxxxxxxxxx",
 "Hash":"yyhhytyutyutuet",
 "validity":null,
 "Type":"basic",
 "Reason":null,
 "Barcodes":{ 
  "results":[ 
     "tetetetetetete"
   ]
 },
 "RelatedBarcodes":{ 
  "results":[ 

  ]
},
 "CustomizedFields":{ 
   "results":[ 

  ]
}}

一切正常,但我收到此错误

HttpClientErrorException: 400 Bad Request.
` at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:94)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:79)
at org.springframework.security.oauth2.client.http.OAuth2ErrorHandler.handleError(OAuth2ErrorHandler.java:172)
at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:730)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:688)
at org.springframework.security.oauth2.client.OAuth2RestTemplate.doExecute(OAuth2RestTemplate.java:128)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:644)
at org.springframework.web.client.RestTemplate.put(RestTemplate.java:459)`

可能是什么问题?

【问题讨论】:

  • 最可能的原因是您正在构建的 URL 中多余的 ' 撇号:Url+"/'"+id
  • @Andreas 网址很好。当我打印它时,它会显示我想使用的 ur。
  • 真的吗?网址http://example.com/foo/'asdfafaff-fsf3-4b1c-a7c4-13352252daa 正确吗?用那个悬空的'?如果这是真的,那真是一个奇怪的 API。
  • @Andreas 我已经删除了它,但我仍然有同样的问题
  • oauth2 错误与身份验证有关。也许您缺少身份验证标头?

标签: java spring-boot resttemplate


【解决方案1】:

当我们不知道您尝试使用的 API 时,无法指出确切的问题是什么。

HTTP状态400表示由于语法无效,服务器无法处理您发送的请求。这是非常笼统的信息,背后可能有无数的原因。

您必须自己弄清楚究竟是什么导致了这种反应。您可以通过查看收到的响应的正文来实现它。由于您尚未声明要使用哪个ResponseErrorHandler,因此已应用默认的DefaultResponseErrorHandler。打开调试模式并在方法public void handleError(ClientHttpResponse response) 上放置一些断点。在那里,您应该能够从响应中获取有关问题所在的更多详细信息,并相应地解决您的请求。

【讨论】:

  • 即使我将其置于带断点的调试模式下,我仍然会收到错误的请求错误。我进行了相同的调用,但使用了不同的 json 和程序中某个其他端点,它可以工作。我真的很困惑为什么这不起作用。
  • 你提取响应的正文了吗?你的问题应该有一个答案,一些关于问题的详细信息。
猜你喜欢
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-19
  • 2020-02-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多