[英]Response from a API from RestTemplate needs to be passed to another in the request body. But it is failing with 400 error
I am trying to pass the response of one API which may contain \n or quotes(") to another API using RestTemplate.我正在尝试使用 RestTemplate 将一个可能包含 \n 或引号(“)的 API 的响应传递给另一个 API。
But it is always failing with 400 error.但它总是因 400 错误而失败。 I guess the post body is broken because of newline and quotes in it.我猜帖子正文由于换行符和引号而损坏。
Can you please suggest how to make it work?你能建议如何使它工作吗?
This is the exception I am getting and my request body looks like:这是我得到的例外,我的请求正文如下所示:
{"to":"test@test.com","replyTo":"test@test.com","body":"call\n"} {"to":"test@test.com","replyTo":"test@test.com","body":"call\n"}
Request URL: http://localhost:8080/endpoint/test, action: POST, status: 400
org.springframework.web.client.HttpClientErrorException: 400 null
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:94)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:79)
at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:775)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:728)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:702)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.j
You need need to create a model like this:您需要像这样创建 model:
class MyModel {
String to;
String replyTo;
String body;
//getters and setters......
}
marshal string into the object like this:像这样将字符串编组到 object 中:
String requestBody="";//{"to":"test@test.com","replyTo":"test@test.com","body":"call\n"}
MyModel myModel=new ObjectMapper().readValue(requestBody, MyModel);
now that you have an object, remove newline characters from the body property.现在您有了 object,从 body 属性中删除换行符。 Like this:像这样:
String s=myModel.getBody().replace('\n', ' ');//you can choose to replace "\n" with whatever you want
myModel.setBody(s);
after that you can deserialise the object like this:之后,您可以像这样反序列化 object:
requestBody=new ObjectMapper().writeValueAsString(myModel);
the send the requestBody
发送requestBody
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.