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

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

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

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

  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS
  • How To Validate HTTP Post Request Body - Restful Web Services With Spring Framework | Spring Boot
  • Leveraging Salesforce Using a Client Written In Angular
  • RESTful Web Services With Spring Boot: Reading HTTP POST Request Body

Trending

  • How to Practice TDD With Kotlin
  • Setting Up Data Pipelines With Snowflake Dynamic Tables
  • Scaling in Practice: Caching and Rate-Limiting With Redis and Next.js
  • Start Coding With Google Cloud Workstations
  1. DZone
  2. Data Engineering
  3. Data
  4. How to Use Spring RESTTemplate to Post Data to a Web Service

How to Use Spring RESTTemplate to Post Data to a Web Service

Learn how easy it is to post objects to your web service by using RESTTemplate with Maven, JUnit, and Log4J with this tutorial.

By 
Johnathan Mark Smith user avatar
Johnathan Mark Smith
·
Aug. 09, 19 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
513.7K Views

Join the DZone community and get the full member experience.

Join For Free

In this example, I am going to show you how to post data to a RESTful web service in Java using Spring, Spring Java Configuration and more.

Web Service Code

Let’s take a quick look at the Spring MVC Web Service code on the server:

@Controller
@RequestMapping("/api")
class JSonController
{

    private static final Logger logger = LoggerFactory.getLogger(JSonController.class);
    @RequestMapping(value = "/{id}", method = RequestMethod.POST)
    @ResponseBody
    public User updateCustomer(@PathVariable("id") String id, @RequestBody User user) {

        logger.debug("I am in the controller and got ID: " + id.toString());
        logger.debug("I am in the controller and got user name: " + user.toString());

        return new User("NEW123", "NEW SMITH");
    }

As you can see from the code above, the web service is going to wait for an ID and user object to be passed in and then it's going to create a new User Object and send it back to the client.

Let's take a quick look inside the User Object:

public class User
{
    private String user;
    private String name;
    public User()
    {
    }

    public User(String user, String name)
    {
        this.user = user;
        this.name = name;
    }

    public String getUser()
    {
        return user;
    }

    public void setUser(String user)
    {
        this.user = user;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }
}

So you can see from the above code that the user object has two fields, user and name.

Time for the Client Code

You can see from the client code below that we are using Spring RESTTemplate and going to post a User Object to a web server and get one back.

@PropertySource("classpath:application.properties")
public class Main
{

    /**
     * Setting up logger
     */
    private static final Logger LOGGER = getLogger(Main.class);
    public static void main(String[] args) throws IOException
    {
        LOGGER.debug("Starting REST Client!!!!");

        /**
         *
         * This is going to setup the REST server configuration in the applicationContext
         * you can see that I am using the new Spring's Java Configuration style and not some OLD XML file
         *
         */
        ApplicationContext context = new AnnotationConfigApplicationContext(RESTConfiguration.class);

        /**
         *
         * We now get a RESTServer bean from the ApplicationContext which has all the data we need to
         * log into the REST service with.
         *
         */
        RESTServer mRESTServer = context.getBean(RESTServer.class);
        /**
         *
         * Setting up data to be sent to REST service
         *
         */
        Map<String, String> vars = new HashMap<String, String>();
        vars.put("id", "JS01");
        /**
         *
         * Doing the REST call and then displaying the data/user object
         *
         */
        try
        {

            /*

                This is code to post and return a user object

             */

            RestTemplate rt = new RestTemplate();
            rt.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
            rt.getMessageConverters().add(new StringHttpMessageConverter());

            String uri = new String("http://" + mRESTServer.getHost() + ":8080/springmvc-resttemplate-test/api/{id}");

            User u = new User();
            u.setName("Johnathan M Smith");
            u.setUser("JS01");

            User returns = rt.postForObject(uri, u, User.class, vars);

            LOGGER.debug("User:  " + u.toString());

        }
        catch (HttpClientErrorException e)
        {
            /**
             *
             * If we get a HTTP Exception display the error message
             */

            LOGGER.error("error:  " + e.getResponseBodyAsString());

            ObjectMapper mapper = new ObjectMapper();
            ErrorHolder eh = mapper.readValue(e.getResponseBodyAsString(), ErrorHolder.class);

            LOGGER.error("error:  " + eh.getErrorMessage());

        }
        catch(Exception e)
        {
            LOGGER.error("error:  " + e.getMessage());

        }
    }

}

You can see from the above code how easy it is to use RESTTeample to post data to a web service.

Where Can I Get the Source Code?

You can check out the project on GitHub.

git clone git@github.com:JohnathanMarkSmith/springmvc-resttemplate-test.git
cd springmvc-resttemplate-test.git
Web Service Spring Framework POST (HTTP) Data (computing) resttemplate

Opinions expressed by DZone contributors are their own.

Related

  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS
  • How To Validate HTTP Post Request Body - Restful Web Services With Spring Framework | Spring Boot
  • Leveraging Salesforce Using a Client Written In Angular
  • RESTful Web Services With Spring Boot: Reading HTTP POST Request Body

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!