我想使用RestTemplate来发出请求。我必须使用 GET 请求发送请求负载。是的,是的,我知道。所以我尝试了 RestTemplate.exchange,但无论如何,它似乎都没有发送 GET 请求的有效负载。因此,我进一步查看了文档和数字 RestTemplate.execute 可能就是我正在寻找的内容......现在我在这里。
因此文档说明了执行:
Execute the HTTP method to the given URI template, preparing the request with the RequestCallback, and reading the response with a ResponseExtractor.
好的。让我们看看RequestCallback
Callback interface for code that operates on a ClientHttpRequest. Allows to manipulate the request headers, and write to the request body. Used internally by the RestTemplate, but also useful for application code.
但是RequestCallback只有一个方法:doWithRequest,它通过ClientHttpRequest接口(interface)接受它的参数...它没有设置方法/操纵请求的正文。可悲的是。 :C
所以,我有两个问题:
- 关于文档,我缺少什么?
- 如何使用 RestTemplate 发出带有负载/请求正文的 GET 请求?
最佳答案
你可以这样做:
public class BodySettingRequestCallback implements RequestCallback {
private String body;
private ObjectMapper objectMapper;
public BodySettingRequestCallback(String body, ObjectMapper objectMapper){
this.body = body;
this.objectMapper = objectMapper;
}
@Override
public void doWithRequest(ClientHttpRequest request) throws IOException {
byte[] json = getEventBytes();
request.getBody().write(json);
}
byte[] getEventBytes() throws JsonProcessingException {
return objectMapper.writeValueAsBytes(body);
}
}
您将在执行方法中使用此 RequestCallback。像这样的东西:
restTemplate.execute(url, HttpMethod.POST, callback, responseExtractor);
关于spring - 如何使用Spring RestTemplate执行设置http请求正文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31250534/