Checkout our demo site to practice selenium https://magento.softwaretestingboard.com/

0 like 0 dislike
508 views
in Programming by
retagged by
I have a scenario where I need to send data using RESTTemplate. How do you post data?

1 Answer

0 like 0 dislike
by The go-to Tester (181 points)
Sample user class:

public class User

{

    private String user;

    private String 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;

    }

}

Time for the Client Code

public class Main

{

    public static void main(String[] args) throws IOException

    {

        /**

         *

         * This is setting the REST server configuration in the applicationContext

         *

         */

        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");

        try

        {

            /*

                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("M Shah");

            u.setUser("MS01");

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

        }

        catch (HttpClientErrorException e)

        {

            ObjectMapper mapper = new ObjectMapper();

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

        }

        catch(Exception e)

        {

        }

    }

}

Comment below if you have any questions/concern.


This site is for software testing professionals, where you can ask all your questions and get answers from 1300+ masters of the profession. Click here to submit yours now!

...