dsplynm
dsplynm

Reputation: 613

How to set http request body using Spring RestTemplate execute?

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.

http://docs.spring.io/spring-framework/docs/3.2.8.RELEASE/javadoc-api/org/springframework/web/client/RestTemplate.html

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.

http://docs.spring.io/spring-framework/docs/3.2.8.RELEASE/javadoc-api/org/springframework/web/client/RequestCallback.html

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

http://docs.spring.io/spring-framework/docs/3.2.8.RELEASE/javadoc-api/org/springframework/http/client/ClientHttpRequest.html

So, I have two questions:

Upvotes: 4

Views: 11048

Answers (1)

de.la.ru
de.la.ru

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

Related Questions