Spring RestTemplate GET with parameters
To perform a GET request with parameters using the RestTemplate
in Spring, you can use the getForObject()
method and pass it a URL with placeholders for the parameters, as well as a map of the parameter values.
Here's an example of how to do this:
import java.util.Collections;
import java.util.Map;
import org.springframework.web.client.RestTemplate;
public class Main {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
String url = "http://example.com/users?id={id}&name={name}";
Map<String, String> params = Collections.singletonMap("id", "123");
params.put("name", "Alice");
String result = restTemplate.getForObject(url, String.class, params);
System.out.println(result);
}
}
This will send a GET request to the URL http://example.com/users?id=123&name=Alice
and print the response.
Note that the getForObject()
method returns an object of the specified type (in this case, a String
). You can use other methods of the RestTemplate
class, such as getForEntity()
, to get more information about the response, including the HTTP status code, headers, and more.
I hope this helps! Let me know if you have any questions.