Cannot send a GET request with RESTTemplate

811 Views Asked by At

I need to send a request as following

 http://server.com/server1/index.php?id=123&name=jack&date=12.1.2016

I am using following code but it seems like it does not send a correct request as response object is empty. I am also wondering how to show the complete url that restTemplate is sending? I know WireShark can be used but is there any way to retrieve it using restTemplate?

Code

String url = "http://server.com/server1/index.php?"
Map<String,String> vars = new HashMap<String,String>();
vars.put("id","123");
vars.put("name","jack");
vars.put("date","12.1.2016");

Profile profile = restTemplate.getForObject(url,Profile.class,vars);
2

There are 2 best solutions below

0
On

You can set the Log Level for org.springframework.web.client.RestTemplate to debug then you'll get an output similar to this:

12:11:22.072 [main] DEBUG o.s.web.client.RestTemplate - Created GET request for "http://echo.jsontest.com/key/value/one/two"
12:11:22.110 [main] DEBUG o.s.web.client.RestTemplate - Setting request Accept header to [application/json, application/*+json]
12:11:24.492 [main] DEBUG o.s.web.client.RestTemplate - GET request for "http://echo.jsontest.com/key/value/one/two" resulted in 200 (OK)
12:11:24.494 [main] DEBUG o.s.web.client.RestTemplate - Reading [class com.example.TestOptional$Echo] as "application/json;charset=ISO-8859-1" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@16f7c8c1]

There you can see the Request the URL and the returned HTTP Status code.

If you are using Logback xml configuration you would write

<logger name="org.springframework.web.client.RestTemplate" level="DEBUG" />
1
On

There are no template variables in this URL template:

String url = "http://server.com/server1/index.php?";

I think you need to specify them explicitly like this:

String url = "http://server.com/server1/index.php?id={id}&name={name}&date={date}";

In this template, id is the name of the query string parameter, and {id} refers to a key in your vars map.

In addition to switching on logging as andih describes, you can instantiate the URL template with a given set of variables as follows:

new UriTemplate(url).expand(vars).toString()