【问题标题】:Http 400 using resttemplate postforobjectHttp 400 使用 resttemplate postforobject
【发布时间】:2019-02-08 13:12:12
【问题描述】:

下面是给出 400 错误请求的代码,尝试了各种选项,但总是以 400 错误请求结束,但是使用 OkHttp 客户端同样有效

HttpHeaders hh = new HttpHeaders();
RestTemplate rt = new RestTemplate();
String reqBody = new ObjectMapper.writeValueAsString(“test msg”);  
headers.set(“Accept”, “text/plain”);  
headers.set(“content-type”,”application/json”);  
headers.set(“authorization”, “Basic xxxxx”);  
headers.set(“ibm-mq-rest-csrf-token”,”blank”);  
HttpEntity<String> request = new HttpEntity<>(reqBody.toString());  
ResponseEntity<Object> result = rt.postForObject(url, request, Object.class);

以下代码使用 okhttp

【问题讨论】:

  • 请提供源代码。不要发布代码图片
  • 您已经向我们展示了有效的代码?你能告诉我们失败的代码吗?另外,我重申不要发布您的代码图像。请复制并粘贴到您的问题中。
  • 对不起图片,下面是代码不工作,收到 400 错误请求
  • RestTemplate rt = new RestTemplate(); HttpHeaders hh = new HttpHeaders(); String reqBody = new ObjectMapper.writeValueAsString(“test msg”); headers.set(“Accept”, “text/plain”); headers.set(“content-type”,”application/json”); headers.set(“authorization”, “Basic xxxxx”); headers.set(“ibm-mq-rest-csrf-token”,”blank”); HttpEntity&lt;String&gt; request = new HttpEntity&lt;&gt;(reqBody.toString()); ResponseEntity&lt;Object&gt; result = rt.postForObject(url, request, Object.class);
  • 我同意您应该编辑问题并包括工作代码。

标签: spring-boot ibm-mq


【解决方案1】:

您的内容似乎不是 JSON,在这两种情况下它似乎都是纯文本。因此标题

Content-Type: text/plain

应该使用而不是

Content-Type: application/json

我不确定为什么这在您的 OKHTTP 示例中有效,除非您用于构建帖子正文的媒体类型以某种方式覆盖了您的 Content-Type 标头?

【讨论】:

  • 感谢您的回复,这也是我的观察结果,今天尝试使用 application/json 发布 JSON 并且它有效,但无法使用 text/plain 发布字符串,最终使用 OkHttp 解决了非常适合发布字符串
  • 您是否更改了这一行。 headers.set(“内容类型”,“应用程序/json”);使用文本/纯文本?结果如何?
  • 是的,我收到了 400 个错误请求,Springboot RestTemplate 仅应用程序/json 出于任何原因都可以工作..
猜你喜欢
  • 1970-01-01
  • 2014-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-09
  • 1970-01-01
  • 2019-03-20
  • 1970-01-01
相关资源
最近更新 更多