DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • Develop a Spring Boot REST API in AWS: PART 4 (CodePipeline / CI/CD)
  • RESTful Web Services: How To Create a Context Path for Spring Boot Application or Web Service
  • How To Validate HTTP Post Request Body - Restful Web Services With Spring Framework | Spring Boot

Trending

  • The Human Side of Logs: What Unstructured Data Is Trying to Tell You
  • 5 Subtle Indicators Your Development Environment Is Under Siege
  • Testing SingleStore's MCP Server
  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring Boot REST Template URI Encoding

Spring Boot REST Template URI Encoding

By 
Siva Prasad Rao Janapati user avatar
Siva Prasad Rao Janapati
·
Allen Coin user avatar
Allen Coin
·
Adiel Isaacs user avatar
Adiel Isaacs
·
Updated Jul. 22, 20 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
50.5K Views

Join the DZone community and get the full member experience.

Join For Free

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
 




x


 
1
StringBuilder builder = new StringBuilder("http://localhost:8080/api/users");
2
URI uri = URI.create(builder.toString());
3
 
          
4
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
 




xxxxxxxxxx
1
11


 
1
StringBuilder builder = new StringBuilder("http://localhost:8080/api/adduser");
2
        builder.append("?username=");
3
builder.append(URLEncoder.encode("john@1.com",StandardCharsets.UTF_8.toString()));
4
        builder.append("&password=");
5
        builder.append(URLEncoder.encode("P@$$word",StandardCharsets.UTF_8.toString()));
6
        builder.append("&phone=");
7
        builder.append(URLEncoder.encode("911",StandardCharsets.UTF_8.toString()));
8
        
9
    URI uri = URI.create(urlencoded);
10
        
11
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
 




xxxxxxxxxx
1
34


 
1
@RequestMapping(value = "/addNewUser", method = RequestMethod.POST)
2
    public ModelAndView processRequest(HttpServletRequest request, HttpSession session, @RequestParam("username")String username, @RequestParam("password")String password, @RequestParam("phone")String phone) {
3
                
4
        RestTemplate restTemplate = new RestTemplate();
5
 
          
6
        Users user = new Users();
7
        user.setUsername(username);
8
        user.setPassword(password);
9
        user.setPhone(phone);
10
        user.setEnabled(true);
11
                
12
        restTemplate.postForObject("http://localhost:8080/api/adduser", user, Users.class);
13
        
14
        StringBuilder builder = new StringBuilder("http://localhost:8080/api/users");
15
        
16
        URI uri = URI.create(builder.toString());
17
        
18
        List<Users> updatedUsers = restTemplate.getForObject(uri, List.class);
19
        
20
        session = request.getSession(false);
21
        ModelAndView model = new ModelAndView();
22
 
          
23
        if(session != null){
24
            model.setViewName("welcome");
25
            
26
            model.addObject("users", updatedUsers);
27
            model.addObject("user", (Users)session.getAttribute("user"));
28
            model.addObject("sessiontracker", sessiontracker.getList());
29
            model.addObject("sumValidSessions", sessiontracker.getSizeSessionList());
30
        
31
            return model;
32
        }
33
        return new ModelAndView("login");
34
    }



The GUI sample i'm using adds a user and displays it in a user table.

Adding a user gui


So, it all depends on which version of Spring you're using. If you're using an old version of Spring, the UriComponentsBuilder with your spring-web jar wont be included. For more information on standard URI 's and encoding click on this link: Java URL Encoding.

Delving into URI 's can get quite complex with Rest Template. Nevertheless, I'll recommend this for a monolithic application or If you want a quick metrics GUI around your microservices data. Don't disregard that Spring allows you to develop two Controller types, a standard MVC Controller, and a Rest Controller, which gives you the capabilities of exposing an API. 

It is favorable nonetheless to use an HTTP client for B2B communications on URLs in a microservice environment, which adds much more customization around exceptions and Response codes. 

I hope this helps to find traction on the route to take and I hope this gives you some variance around Spring Boot Rest API.

Thank you! 

Uniform Resource Identifier Spring Framework Spring Boot REST Web Protocols Template

Opinions expressed by DZone contributors are their own.

Related

  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • Develop a Spring Boot REST API in AWS: PART 4 (CodePipeline / CI/CD)
  • RESTful Web Services: How To Create a Context Path for Spring Boot Application or Web Service
  • How To Validate HTTP Post Request Body - Restful Web Services With Spring Framework | Spring Boot

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!