javaspring-mvcurlresttemplatevictoriametrics

How to pass %22 as filter in restTemplate in Spring MVC


1.requestURL = https://test.env123.com:8081/select/0/prometheus/api/v1/query_range?query=test.link.packets{billid=%22P1yhABCnWJ7WhI%22}&start=2023-08-10T01:02:03Z&end=2023-08-26T01:02:03Z

ResponseEntity result = restTemplate.getForEntity(requestURL, String.class);

  1. String filter = ""; requestURL = https://test.env123.com:8081/select/0/prometheus/api/v1/query_range?query=test.link.packets{filter}&start=2023-08-10T01:02:03Z&end=2023-08-26T01:02:03Z

filter = "{billid=%22P1yhABCnWJ7WhI%22}";

ResponseEntity result = restTemplate.exchange(requestURL, HttpMethod.GET, request, String.class, filter);

I tried both the ways, none of them worked.

throws this exception: java.lang.IllegalArgumentException: Not enough variable values available to expand 'billid=%22P1yhABCnWJ7WhI%22'

How do I resolve such cases specially when URL has double quotes " and curly braces { } ?


Solution

  • when You are trying to send get requests with get parameters which contain some of the special symbols like &, {, }, ? and others you have to UrlEncode them, becaus when server sees & as eaxmple, he recognises it as and of previous parameter and waits for another parameter. Try pls to UrlEncode these params.

    Here is an example, You can use UriComponentsBuilder

    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters()
                .add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));
    
    String baseUrl = "YOUR_API_URL";
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(baseUrl)
                .queryParam("query","test.link.packets{filter}")
                .queryParam("start","2023-08-10T01:02:03Z")
                .queryParam("end","2023-08-26T01:02:03Z");
    
    ResponseEntity<String> response = restTemplate.getForEntity(builder.toUriString(), String.class);
    

    UPDATED

    Here is another approach which will also work great. But note, if you are passing paramters into the url in this way, order matters, rest template will pass these params to the url, in order how they are passed in getForEntity function

    // Create a RestTemplate instance
    RestTemplate restTemplate = new RestTemplate();
    String start = "2023-08-10T01:02:03Z";
    String end = "2023-08-26T01:02:03Z";
    String filter = "{billid=\"P1yhABCnWJ7WhI\"}";
    // Define the URL with parameters or build it
    String baseUrl = "https://play.victoriametrics.com/select/0/prometheus/api/v1/query_range?query=test.link.packets{filter}&start={start}&end={end}";
    // Make the GET request and receive the response as ResponseEntity
    ResponseEntity<String> response = restTemplate.getForEntity(baseUrl, String.class, filter, start, end);