preface

The basic package uses Lombok (a convenient object construction tool get/set) and spring-boot-starter-web. SpringBoot is used only to build Sample project quickly. It has no impact on learning the corresponding functions of Spring.

We hope that you have a certain Java foundation and understand a favorite IDEA function, thank you.

To construct the Demo

Will build an application using the Spring, so that the RestTemplate retrieve random SpringBoot reference at http://gturnquist-quoters.cfapps.io/api/random.

Obtaining REST Resources

Once the project is set up, you can create a simple application that uses RESTful services.

RESTful services has stood up on the http://gturnquist-quoters.cfapps.io/api/random. It randomly picks up references to Spring Boot and returns them as JSON documents.

If you request this URL through a Web browser or curl, you will receive a JSON document like this:

{

type: success,

value: {

id: 4,

quote: Previous to Spring Boot, I remember XML hell, confusing set up, and many hours of frustration.

}

}

Easy, but not very useful when retrieved from a browser or through crimp.

A more useful way to programmatically use REST Web services. To help you with this task, Spring provides a convenient template class, RestTemplate. RestTemplate makes interaction with most RESTful services a one-line mantra. It can even bind data to custom domain types.

First, create a domain class that contains the required data.

@Data

@NoArgsConstructor

@AllArgsConstructor

@JsonIgnoreProperties(ignoreUnknown = true)

public class Quote {

private String type;

private Value value;

@Override

public String toString() {

return Quote{ +

type=’ + type + ‘\” +

, value= + value +

‘} ‘;

}

}

As you can see, this is a simple Java class with properties and getter methods for matching. It USES @ JsonIgnorePropertiesJackson JSON processing library for comments, to indicate that should ignore this type of unbounded any attributes.

To bind data directly to a custom type, you need to specify the exact same variable name as the key in the JSON document returned from the API. If the variable names and keys in your JSON doc do not match, you need to specify the exact key of the JSON document using the @jsonProperty annotation.

Embedding an internal reference itself requires an additional class.

@Data

@NoArgsConstructor

@AllArgsConstructor

@JsonIgnoreProperties(ignoreUnknown = true)

public class Value {

private Long id;

private String quote;

@Override

public String toString() {

return Value{ +

id= + id +

, quote=’ + quote + ‘\” +

‘} ‘;

}

}

It uses the same annotations, but only maps to other data fields.

Make the application executable

While it is possible to package this service as a traditional WAR file for deployment to an external application server, the simpler approach demonstrated below creates a standalone application. You package everything in an executable JAR file, driven by a good old Java main() method. In doing so, you used Spring’s support to embed the Tomcat servlet container as an HTTP runtime rather than deploying it to an external instance.

Now you can write the Application class for RestTemplate to get data from the Spring Boot quote service.

@Slf4j

public class Application {

public static void main(String[] args) {

RestTemplate restTemplate = new RestTemplate();

Quote quote = restTemplate.getForObject(http://gturnquist-quoters.cfapps.io/api/random, Quote.class);

log.info(quote.toString());

}

}

Since the Jackson JSON processing library is in the classpath, RestTemplate uses it (via the message converter) to convert incoming JSON data into Quote objects. From there, the contents of the Quote object are logged to the console.

In this case, you only use the RestTemplate to make HTTP GET requests. But RestTemplate also supports other HTTP verbs, such as POST, PUT, and DELETE.

Use Spring Boot to manage the application life cycle

So far, we haven’t used Spring Boot in our applications, but there are some advantages to doing so, and it’s not hard to do. One advantage is that we might want Spring Boot to manage the message converter RestTemplate, making it easy to add customizations declaratively. To do this, we @SpringBootApplication use and transform the main method on the main class to start it, just as we would in any SpringBoot application. Finally, we move its RestTemplate to the CommandLineRunner callback to be executed by Spring Boot at Boot time:

@Slf4j

@SpringBootApplication

public class RestTemplateApplication {

public static void main(String[] args) {

SpringApplication.run(RestTemplateApplication.class, args);

}

@Bean

public RestTemplate restTemplate(RestTemplateBuilder builder){

return builder.build();

}

@Bean

public CommandLineRunner run(RestTemplate restTemplate) throws Exception{

return args – {

Quote quote = restTemplate.getForObject(http://gturnquist-quoters.cfapps.io/api/random, Quote.class);

log.info(quote.toString());

};

}

}

Its RestTemplateBuilder is injected by Spring, and if you use it to create a RestTemplate then you will benefit from all the automatic configuration in Spring Boot with the message converter and request factory. We also extract the RestTemplate as an a@Bean to make it easier to test (which makes it easier to simulate this way).

The results of

You should see the following output, quoted randomly:

The 2018-11-22 10:32:13. 19104-284 the INFO [the main] C.G.U.R estTemplateApplication: Quote{type=’success’, value=Value{id=11, quote=’I have two hours today to build an app from scratch. @springboot to the rescue! ‘}}

If you see errors, Could not extract response: No suitable HttpMessageConverter found for Response type [class hello.quote] Then you may be in an environment where you cannot connect to the back-end service (if you can access it, JSON will be sent). Maybe you’re behind the company’s agent? Try setting the standard system properties http.proxyHost and http.proxyPort to appropriate values for your environment.

At the end

A: congratulations! You just developed a simple REST client using Spring.