SoFunction
Updated on 2025-04-14

Resttemplate to set params

How to set request parameters using RestTemplate

The way RestTemplate sets request parameters varies according to the request type (GET/POST) and parameter form (path parameters, query parameters, JSON request body). The following is the specific implementation method:

1. GET request parameter settings

Path parameters
Use placeholders{param},passMapOr variable parameter passing:

// Use Map to pass parametersMap<String, String> uriVariables = new HashMap<>();
("id", "123");
String result = ("/api/{id}", , uriVariables);
// Or use variable parametersString result = ("/api/{id}", , "123");

Query parameters
useUriComponentsBuilderBuild a URL with parameters:

UriComponentsBuilder builder = ("/api/data")
    .queryParam("name", "John")
    .queryParam("age", 25);
String url = ();
String result = (url, );

2. POST request parameter setting

JSON request body
useHttpEntityEncapsulate nested JSON parameters and set the request header:

// Build nested parametersMap<String, Object> paramMap = new HashMap<>();
Map<String, String> queryMap = new HashMap<>();
("c1", "value1");
("a", "valueA");
("b", queryMap);
// Set request headerHttpHeaders headers = new HttpHeaders();
(MediaType.APPLICATION_JSON);
HttpEntity<Map<String, Object>> entity = new HttpEntity<>(paramMap, headers);
// Send a requestString response = ("/api", entity, );

References to the multi-layer nested JSON construction method in the example.

Form parameters
useMultiValueMapPass form data:

HttpHeaders headers = new HttpHeaders();
(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
("username", "admin");
("password", "123456");
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(formData, headers);
ResponseEntity<String> response = ("/login", entity, );

3. Configure RestTemplate timeout (optional)

Set connection and read timeouts through configuration classes:

@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        (10000); // 10 seconds        (10000);    // 10 seconds        return new RestTemplate(factory);
    }
}

Reference configuration class example.

4. Handle complex responses

Parses JSON response and extracts data:

ResponseEntity<String> response = (url, , entity, );
JSONObject jsonResponse = new JSONObject(());
if ("0000".equals(("parameter").getString("code"))) {
    String result = ("result");
}

Reference response processing method.

This is the article about how to set up params in resttemplate. For more related content on resttemplate setting params, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!