Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass queries to a url in rest template without uri

I am trying to make a GET call to a url and I need to pass in queries to get the response i want. I am using spring framework and using Rest template to make the calls. I know i can manually do this way:

Uritemplate(url+name={name}...

but this is a pain. I need a easier way and the hash map will be generated dynamically

So how do i pass in a map to a url without using uri encoder?

 String url = "example.com/search
 Map<String, String> params = new HashMap<String, String>();
          params.put("name", "john");
          params.put("location", "africa");

public static ResponseEntity<String> callGetService(String url, Map<String, String> param) {
        RestTemplate rest = new RestTemplate();
        rest.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

        HttpEntity<?> reqentity = new HttpEntity<Object>(headers);

        ResponseEntity<String> resp = rest.exchange(url, HttpMethod.GET, reqentity, String.class);
        System.out.println(resp);
        return resp;
    }

So url will end up like this example.com/search?name=john&location=africa
response: {name:john doe, love: football} --- tons of json data

like image 454
РАВИ Avatar asked Dec 02 '22 20:12

РАВИ


1 Answers

You can use UriComponentsBuilder and UriComponents which facilitate making URIs

String url = "http://example.com/search";
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("name", "john");
params.add("location", "africa");

UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(url).queryParams(params).build();
System.out.println(uriComponents.toUri());

prints

http://example.com/search?name=john&location=africa

There are other options if you need to use URI variables for path segments.

Note that if you are sending an HTTP request, you need an valid URL. The HTTP URL schema is explained in the HTTP specification, here. The UriComponentsBuilder provides methods to build all parts of the URL.

like image 174
Sotirios Delimanolis Avatar answered Dec 25 '22 17:12

Sotirios Delimanolis