Accessing REST services based on Spring

We have previously learned how to easily convert data in a relational database into information accessible by REST services, easy and freehand examples . It is also very simple to access REST services based on Spring. You only need to annotate POJOs, which RestTemplatecan be easily done through the ones provided by Spring. Let's find out.

development environment

  • IDE+Java environment (JDK 1.7 or above)
  • Maven 3.0+ (built-in in Eclipse and Idea IntelliJ, if you use IDE and don't use command line tools, you can not install it)

The POM file is as follows:

 

<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.tianmaying</groupId>
  <artifactId>rest-service-consuming</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>rest-service-consuming</name>
  <description>demo of consuming rest service by spring RestTemplate</description>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.5.RELEASE</version>
    <relativePath/>
  </parent>

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

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency> 
    <dependency>
      <groupId>org.springframework.mobile</groupId>
      <artifactId>spring-mobile-device</artifactId>
    </dependency> 
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.16.2</version>
      <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>

The jackson-databind package provides auxiliary functions for converting JSon objects into Java classes. The lombok package provides simple annotations to help us simplify and eliminate some must-have but bloated java code, such as getters, setters, and constructors. These functions are generally automatically generated by the IDE, and can be easily done with three or two lombok annotations.

hint

In order for Eclipse to recognize lombok, in addition to importing the lombok JAR package, you need to install lombok so that Eclipse will not report a warning (otherwise, even if you mark it @Data, if you don't write setter and getter code, Eclipse will warn you). The installation is very simple, just download it from the lombok website , and then double-click the Jar package to run it.

Automatically convert JSON to POJO

We assume the JSON format returned by the REST service is as follows:

 

{
  id:100
  name: "zhangsan"
  address: {
    city: "beijing"
    steet: "yiheyuan lu 5"
  }
}

Correspondingly we create two new classes to store the information in JSON

User.java

 

package com.tianmaying.springboot.restconsuming;

import lombok.Data;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class User {
    private Long id;
    private String name;
    private Address address;
}

Address.java

 

package com.tianmaying.springboot.restconsuming;

import lombok.Data;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class Address {
    private String city;
    private String street;
}

Both classes above have two annotations @Dataand @JsonIgnorePoperties. in:

  • @DatatoStringAnnotations provide getters, setters and methods for each class
  • @JsonIgnorePopertiesThe annotation provided by Jackson's JSON processing library, indicating that any properties not bound to this class can be ignored.

访问REST服务

Spring提供一个模板类RestTemplate来调用REST Web服务,通过这个类你只需要一行代码即可完成调用,而且将返回的JSON数据自动绑定到类的属性。

App.java

 

package com.tianmaying.springboot.restconsuming;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class App implements CommandLineRunner {

    private static final Logger log = LoggerFactory.getLogger(App.class);

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

    @Override
    public void run(String... strings) throws Exception {
        RestTemplate restTemplate = new RestTemplate();
        User user = restTemplate.getForObject("http://tianmaying.com/mockapi/user/1", User.class);
        log.info(user.toString());
    }
}

因为Jackson JSON处理包在类路径中,RestTemplate会基于它将REST服务返回的JSON数据转换成一个User对象。

这里只演示了GET请求,基于RestTemplate你可以进行POSTPUT和 DELETE请求,大家去试验一下吧!

 

 

https://www.tianmaying.com/tutorial/spring-rest-consuming

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326947530&siteId=291194637