3. Consume a restful Web Service

Source: Internet
Author: User

In this lesson, we learn how to consume (Invoke) a RESTful Web Service based on our official website tutorials. Original link https://spring.io/guides/gs/consuming-rest/

This guide walks you through the process of creating an application that uses a RESTful Web service.

What are we going to create?

You will build an application that uses spring resttemplate to retrieve the random spring boot reference from the Http://gturnquist-quoters.cfapps.io/api/random.

What do you need to prepare?
    • JDK1.8 or higher

    • Gradle 4+ or Maven 3.2+

    • You can also import code directly into your IDE.

      • Spring Tool Suite (STS)

      • IntelliJ idea

How do I complete this guide?

There are many ways to do this, and here we do this only through Sts.

Reference link https://spring.io/guides/gs/sts/

1. Open our STS and click File ———— > New ———— > Import Spring Getting Started Content in the upper left corner

2. We enter rest here to search for "consuming rest"

Tips: The type of build that is selected here is the MAVEN project, Code sets two is checked, which generates two project.

Complete means that the code,initial that have been written is initialized with an empty project, and we will modify and try it later in this empty project.

3. By completing the project setup, you can create a simple application that uses restful services.

A restful service has stood up in Http://gturnquist-quoters.cfapps.io/api/random. It randomly extracts references to spring boot and returns them as JSON documents.

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

{"type": "Success", "value": {"id": 2, "quote": "With the Boot you deploy everywhere you can find a JVM basically."}}

It's simple, but it's not very useful when you get it through a browser. Use rest Web Services programmatically in a more useful way.

To help you with this task, spring provides a handy template class called Resttemplate. Resttemplate enables most restful services to interact with a single-line spell. It can even bind the data to a custom field type.

4. First we need to create a domain entity class

 PackageHello;Importcom.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties (Ignoreunknown=true) Public classQuote {PrivateString type; Privatevalue value;  PublicQuote () {} PublicString GetType () {returntype; }     Public voidsetType (String type) { This. Type =type; }     PublicValue GetValue () {returnvalue; }     Public voidSetValue (value value) { This. Value =value; } @Override PublicString toString () {return"quote{" + "type=" + type + ' \ ' + ", value=" + Value + '} '; }}

As you can see, this is a simple Java class that has some properties and matching getter methods. It is annotated with @jsonignoreproperties in the Jackson JSON processing library to indicate that any attributes that are not bound to this type should be ignored.

To bind data directly to a custom type, you need to specify that the variable name is exactly the same as the key in the JSON document returned from the API. If the variable names and keys in the JSON document do not match, you need to use @JsonProperty annotations to specify the exact keys for the JSON document.

Tips: Note that the field names in the JSON returned above are type and value so here we define the type and value.

5. Additional classes are required to embed the internal quote itself.

 PackageHello;Importcom.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties (Ignoreunknown=true) Public classValue {PrivateLong ID; PrivateString Quote;  PublicValue () {} PublicLong getId () {return  This. ID; }     PublicString getquote () {return  This. Quote; }     Public voidsetId (Long id) { This. ID =ID; }     Public voidsetquote (String quote) { This. Quote =quote; } @Override PublicString toString () {return"value{" + "id=" + ID + ", quote= ' + quote + ' \ ' + '} '; }}

Tips: Since value in the JSON returned above is an object containing ID and quote, we need an extra class to define it here.

6. Make this application executable

Although this service can be packaged as a traditional war file for deployment to an external application server, the simpler approach shown below creates a standalone application. You package everything into a separate, executable jar file, driven by a good old Java main () method. Along the journey, you use spring's support to embed the Tomcat servlet container as an HTTP runtime instead of deploying to an external instance.

You can now write a application class that uses Resttemplate to get data from the Spring boot quote service.

 PackageHello;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;Importorg.springframework.web.client.RestTemplate; Public classApplication {Private Static FinalLogger log = Loggerfactory.getlogger (application.class);  Public Static voidMain (string[] args) {//TODO auto-generated Method StubResttemplate resttemplate =Newresttemplate (); Quote Quote= Resttemplate.getforobject ("Http://gturnquist-quoters.cfapps.io/api/random", Quote.class);    Log.info (Quote.tostring ()); }}

Tips: Here we can see that by means of a Resttemplate object, we consume (invoke) the data of another Restfule Web service. With this method of invocation, we will no longer need to write the HttpClient method to handle the call.

Because the Jackson JSON processing library is located in the Classpath, Resttemplate will use it (via a message converter) to convert the incoming JSON data into a quote object. From there, the contents of the quote object are logged to the console.

Here, you only use Resttemplate for HTTP GET requests. However, Resttemplate also supports other HTTP verbs, such as post,put and delete.

Print the console:

7. Managing the application lifecycle with spring boot

So far, we haven't used spring Boot in our application, but there are some advantages, and it's not that hard. One advantage is that we might want to have spring boot manage the message converters in resttemplate so that customizations are easily added declaratively. To do this, we use @springbootapplication on the main class and convert the primary method to start it, just like in any spring boot application. Finally, we move the resttemplate to a Commandlinerunner callback function to be executed at startup by spring Boot:

Src/main/java/hello/application.java

 PackageHello;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;ImportOrg.springframework.boot.CommandLineRunner;Importorg.springframework.boot.SpringApplication;Importorg.springframework.boot.autoconfigure.SpringBootApplication;ImportOrg.springframework.boot.web.client.RestTemplateBuilder;ImportOrg.springframework.context.annotation.Bean;Importorg.springframework.web.client.RestTemplate; @SpringBootApplication Public classApplication {Private Static FinalLogger log = Loggerfactory.getlogger (application.class);  Public Static voidMain (string[] args) {//TODO auto-generated Method StubSpringapplication.run (Application.class); //resttemplate resttemplate = new Resttemplate ();//Quote Quote = Resttemplate.getforobject ("Http://gturnquist-quoters.cfapps.io/api/random", quote.class);//Log.info (quote.tostring ());} @Bean Publicresttemplate resttemplate (Resttemplatebuilder builder) {returnBuilder.build (); } @Bean PublicCommandlinerunner Run (resttemplate resttemplate)throwsException {returnArgs-{Quote Quote= Resttemplate.getforobject ("Http://gturnquist-quoters.cfapps.io/api/random", Quote.class);        Log.info (Quote.tostring ());    }; }}

Tips: The way that was obviously not elegant, we commented out the content just to change to use the spring Boot code to see. In this way, it is obvious that other restful Web service is called more gracefully.

Resttemplatebuilder is injected by spring, and if you use it to create resttemplate, you will benefit from spring boot using all the automatic configuration of the message converter and request factory.

We also extracted the resttemplate into the @bean to make it easier to test (which makes it easier to simulate).

8. Compiling an executable jar

You can use Gradle or maven to run the application from the command line. Or you can build an executable jar file that contains all of the required dependencies, classes, and resources, and run the file. This makes it easy to publish, release, and deploy services as applications across different environments throughout the development lifecycle.

In this step we use the tools integrated in the STS to operate an executable jar:

Then we should be able to see one more file under the target folder.

If you are using Gradle, you can use the./gradlew Bootrun to run the application. Or you can build a build jar file using./gradlew. Then you can run the jar file:

Java-jar Build/libs/gs-consuming-rest-0.1.0.jar

If you are using MAVEN, you can use the./MVNW Spring-boot:run to run the application. Alternatively, you can build the jar file using the./MVNW Clean package. Then you can run the jar file:

Java-jar Target/gs-consuming-rest-0.1.0.jar

The above procedure creates a runnable jar. You can also choose to build a classic war file.

You should see the output shown below and randomly refer to:

If you see the error cannot extract the response: No appropriate httpmessageconverter was found for the response type [class Hello. Quote], then you might be in an environment where you can't connect to the backend service (it will send JSON if you can). Maybe you're behind a company agent? Try setting the standard system Properties Http.proxyhost and Http.proxyport to the values that are appropriate for your environment.

All right, this is the end of this lesson, and in this lesson we find that the most primitive way to invoke the service between the services in spring Boot is actually called in this manner.

Source: Https://github.com/geekxingyun/JavaEE-Framework-Sample/tree/master/Spring-Consume-Restful-Web-Service-Sample

3. Consume a restful Web Service

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.