Hard coding a URI endpoint for the Rest template interface is preferably the first point of reference when implementing a micro service or a monolith application.
There is no easy way to do this!
URI variables are usually meant for path elements, query string parameters, or when you decouple your application from your front-end. Ideally, you’d find a better solution for constructing your URI to access data on various endpoints. But, after doing a couple of endpoint hits, you’ll probably run into a funny looking error like
**org.springframework.web.client.ResourceAccessException: I/O error: **http://localhost:8080%api%users
Regardless of all the research, the URI package comes in quite handy with String Builder to Query a API. There are a few ways of implementing this:
Java
StringBuilder builder = new StringBuilder("http://localhost:8080/api/users");
URI uri = URI.create(builder.toString());
List<Users> updatedUsers = restTemplate.getForObject(uri, List.class);
This returns a list of users on a GET request in the Rest Template. If you’re using the POST request, append your parameters in a string builder like in the snippet below:
Java
StringBuilder builder = new StringBuilder("http://localhost:8080/api/adduser");
builder.append("?username=");
builder.append(URLEncoder.encode("john@1.com",StandardCharsets.UTF_8.toString()));
builder.append("&password=");
builder.append(URLEncoder.encode("P@$$word",StandardCharsets.UTF_8.toString()));
builder.append("&phone=");
builder.append(URLEncoder.encode("911",StandardCharsets.UTF_8.toString()));
URI uri = URI.create(urlencoded);
restTemplate.postForObject(uri, Users.class);
If using special characters, you might want to use the URL encoder on specific charsets. In this case, we’re using UTF_8. This is a huge question mark around just submitting a hard coded URL or how the Rest template behaves.
OR the easiest way is to simply just submit an object on a hard coded URI for your POST Query.
#java #high-perf #spring boot #microservice #spring mvc #tips & # tricks #url encoder / decoder