当我执行以下代码时,出现类似
的错误 "org.springframework.web.client.HttpClientErrorException: 400 null"
。
但是当我用邮递员称呼这个“ http://localhost:2018/test”时,它就起作用了。
static final String URL_EMPLOYEES = "http://localhost:2018/test";
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(new MediaType[] {
MediaType.APPLICATION_JSON}));
// Request to return XML format
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("replyMsg", "str");
// HttpEntity<Employee[]>: To get result as Employee[].
HttpEntity<String> entity = new HttpEntity<String>(headers);
// RestTemplate
RestTemplate restTemplate = new RestTemplate();
// Send request with GET method, and Headers.
ResponseEntity<String> response =
restTemplate.exchange(URL_EMPLOYEES,
HttpMethod.POST, entity,String.class);
HttpStatus statusCode = response.getStatusCode();
// Status Code: 200
if (statusCode == HttpStatus.OK) {
// Response Body Data
msg=response.getBody();
if (msg != null) {
System.out.println(msg);
}
}
//my clint controller class
@RestController
public class TextController {
@RequestMapping(value="/test",method = RequestMethod.POST)
public String myData2(@RequestBody String payload) {
return "done";
}
}
有任何建议吗?
答案 0 :(得分:0)
如果您使用Jackson作为JSON解析器,则只需声明类型为TextNode
的参数即可。这是表示JSON字符串的Jackson类型。
public String updateName(@PathVariable(MY_ID) String myId, @RequestBody TextNode name) {
然后可以使用其asText
方法检索其文本值。
答案 1 :(得分:0)
在这里,您设置类型为{{1}的标头Content-Type
并传递类型为JSON
的正文。
text/String
因此,首先您需要将其更改为
headers.setContentType(MediaType.APPLICATION_JSON); //setting your Content type as JSON.
并在此行之后添加一些代码
headers.setContentType(MediaType.TEXT_PLAIN); //setting your Content type as Pure Text String.
添加此代码
// HttpEntity<Employee[]>: To get result as Employee[].
HttpEntity<String> entity = new HttpEntity<String>(headers);
这可能对您有用。。谢谢:)