Loading
 
What's Next: View All Tutorial →

Spring boot Rest Client Example using RESTTemplate to Post and GET Data with JSON and XML Serialization to Object

A simple program using RESTTemplate to Post and GET  Data with JSON and XML Serialization to Object This consume the webserivce created from this article http://www.catchmycity.com/tutorial...

Published Date: 05/09/2018  Last Modified Date: 05/09/2018    New Post



A simple program using RESTTemplate to Post and GET  Data with JSON and XML Serialization to Object

This consume the webserivce created from this article

http://www.catchmycity.com/tutorial/spring-boot-spring-boot-microservice-using-restcontroller-and-produces-json-and-xml-response_135

Maven Dependency


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.demo</groupId>
    <artifactId>spring-boot-restclient</artifactId>
    <version>1.0</version>
    <packaging>war</packaging>

    <name>spring-boot-restclient</name>
    <description>Demo project for Spring Boot Web MVC</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>       
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>



application.properties

#To remove tomcat server running 
spring.main.web-application-type=none


Employee.java 
 

package com.demo.spring;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "Employee")
public class Employee {

    private String name;

    private String city;

    public Employee() {

    }

    public Employee(String name, String city) {
        this.name = name;
        this.city = city;

    }

    public String getName() {
        return name;
    }

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

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

}



Application.java

package com.demo.spring;

import java.util.ArrayList;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class Application {

	private static final Logger LOGGER = LoggerFactory.getLogger(Application.class);

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);

		String stringResponse = getStringResponse();

		LOGGER.info(stringResponse);

		Employee emp = getEmployeeObjectFromJSON();

		LOGGER.info("Name:" + emp.getName());
		LOGGER.info("City:" + emp.getCity());

		Employee empXmp = getEmployeeObjectFromXML();
		LOGGER.info("Name:" + empXmp.getName());
		LOGGER.info("City:" + empXmp.getCity());

		Employee postEmp = postJsonAndGetXMLEmployeeObject(new Employee("Peter", "New York"));
		LOGGER.info("Name:" + postEmp.getName());
		LOGGER.info("City:" + postEmp.getCity());

	}

	public static String getStringResponse() {
		HttpHeaders header = new HttpHeaders();
		header.set("Accept", "application/json");
		HttpEntity req = new HttpEntity(header);

		RestTemplate restTemplate = new RestTemplate();

		ResponseEntity<String> response = restTemplate.exchange("http://localhost:8080/getJson", HttpMethod.GET, req,
				String.class);

		return response.getBody();
	}

	public static Employee getEmployeeObjectFromJSON() {
		HttpHeaders header = new HttpHeaders();
		header.set("Accept", "application/json");
		HttpEntity req = new HttpEntity(header);

		RestTemplate restTemplate = new RestTemplate();

		ResponseEntity<Employee> empResponse = restTemplate.exchange("http://localhost:8080/getJson", HttpMethod.GET,
				req, Employee.class);

		Employee emp = empResponse.getBody();
		return emp;

	}

	public static Employee getEmployeeObjectFromXML() {
		HttpHeaders header = new HttpHeaders();
		header.setAccept(Arrays.asList(MediaType.APPLICATION_XML));
		HttpEntity req = new HttpEntity(header);

		RestTemplate restTemplate = new RestTemplate();

		ResponseEntity<Employee> empResponse = restTemplate.exchange("http://localhost:8080/getXML", HttpMethod.GET,
				req, Employee.class);

		Employee emp = empResponse.getBody();
		return emp;

	}

	public static Employee postJsonAndGetXMLEmployeeObject(Employee empEntity) {
		HttpHeaders header = new HttpHeaders();
        header.setAccept(Arrays.asList(MediaType.APPLICATION_XML));  // Spring understand the response is xml and JAXB convert to employee object
		header.setContentType((MediaType.APPLICATION_JSON));
		HttpEntity req = new HttpEntity(empEntity, header);

		RestTemplate restTemplate = new RestTemplate();

		ResponseEntity<Employee> empResponse = restTemplate.exchange("http://localhost:8080/saveEmployee",
				HttpMethod.POST, req, Employee.class);

		Employee emp = empResponse.getBody();
		return emp;

	}

}
 
header.setAccept(Arrays.asList(MediaType.APPLICATION_XML));  // Spring understand the response is xml and JAXB convert to employee object
 

Output

 
05-09-2018 17:45:02.612 [main] INFO  com.demo.spring.Application.logStarted - Started Application in 2.12 seconds (JVM running for 2.661)
05-09-2018 17:45:02.702 [main] INFO  com.demo.spring.Application.main - {"name":"John","city":"chennai"}
05-09-2018 17:45:02.768 [main] INFO  com.demo.spring.Application.main - Name:John
05-09-2018 17:45:02.768 [main] INFO  com.demo.spring.Application.main - City:chennai
05-09-2018 17:45:02.840 [main] INFO  com.demo.spring.Application.main - Name:John
05-09-2018 17:45:02.840 [main] INFO  com.demo.spring.Application.main - City:chennai
05-09-2018 17:45:02.873 [main] INFO  com.demo.spring.Application.main - Name:Peter
05-09-2018 17:45:02.873 [main] INFO  com.demo.spring.Application.main - City:New York

 
Awaiting for Administrator approval




← Back to list


Related Post




×