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.