首页 > 解决方案 > Http 400 使用 resttemplate postforobject

问题描述

下面是给出 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 在此处输入图像描述

标签: spring-bootibm-mq

解决方案


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

Content-Type: text/plain

应该使用而不是

Content-Type: application/json

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


推荐阅读