Reputation: 613
I'd like to use RestTemplate to issue requests. I must send a request payload with a GET request. Yeah-yeah, I know. So I tried RestTemplate.exchange, but it seems it is not sending the payload for GET requests, no matter what. So I looked further in the docs and figures RestTemplate.execute might be what I am looking for ... and now here I am.
So the doc states about execute:
Execute the HTTP method to the given URI template, preparing the request with the RequestCallback, and reading the response with a ResponseExtractor.
Okay. Let's see 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.
But RequestCallback has one method only: doWithRequest, which accepts it's parameter through the ClientHttpRequest interface... which has no methods for setting/manipulating the body of the request. Sadly. :C
So, I have two questions:
Upvotes: 4
Views: 11048
Reputation: 3144
You can do it like this:
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);
}
}
You are going to use this RequestCallback in your execute method. Something like:
restTemplate.execute(url, HttpMethod.POST, callback, responseExtractor);
Upvotes: 2