0

I am trying to send a HTTP request using RestTemplate's exchange method. However, for some reason the HTTP body of the sent request seems to be empty.

Here is the code I currently have (the original code is more complex):

package somepackage;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.web.client.RestTemplate;

public class SomeMainClass {
    public static void main(String[] args) {
        HttpEntity<String> entity = new HttpEntity<>("body contents", new HttpHeaders());
        new RestTemplate().exchange("http://localhost:5678/someRequest", HttpMethod.GET, entity, String.class);
    }
}

In order to confirm whether the code above worked, I ran nc -l 5678 (which listens for a request on port 5678) in a terminal, and in my IDE, I ran the above code. The nc command in my terminal printed out a HTTP request that does not have a body (I expected it to have a body with the string "body contents").

Why doesn't this work? How can I fix it?

Note: Here are the requirements that made me decide to use the exchange method

  • It has to be a GET request.
  • The request needs to have a body.
  • I have to set some headers.
  • I need to read the body of the response.
  • 1
    An HTTP server can choose to ignore the body of a GET request. See https://stackoverflow.com/questions/978061/http-get-with-request-body – Sotirios Delimanolis Aug 22 '18 at 00:55
  • 1
    can you try elaborating on why you believe you should use a `GET` request and include a body? Maybe there is a better approach to your problem. – junvar Aug 22 '18 at 01:02
  • @junvar The REST service I'm implementing gives out AWS S3 pre-signed URLs. (They are dynamically generated URLs that expire after some time.) I am using the URLs to download static files (or at least files that are generally static) (hence the GET method). I need to pass in the expiration time as a parameter (hence the body), and I am unsure if I need other parameters (I might do some authentication later). Everything else in my REST service uses JSON parameters, and it would be really weird if there's this one thing that uses something else. – Theemathas Chirananthavat Aug 22 '18 at 01:08
  • 1
    not sure if it's the best way, but you can add the expiry time in the url like `http://localhost:5678/someRequest?expiry=23000` – Kartik Aug 22 '18 at 01:11
  • @Kartik I guess I'll do what you said. – Theemathas Chirananthavat Aug 22 '18 at 18:18

1 Answers1

0

GET methods don't have body. You might want to change HttpMethod.GET to HttpMethod.POST.

If you want to supply parameters in GET, you can change the URL to something like http://localhost:5678/someRequest?expiry=23000. More details at Spring RestTemplate GET with parameters.

Kartik
  • 7,194
  • 3
  • 23
  • 43