Spring-boot-rest-template

提供:Dev Guides
移動先:案内検索

春のブーツ-残りのテンプレート

RESTテンプレートは、RESTful Webサービスを使用するアプリケーションを作成するために使用されます。 * exchange()*メソッドを使用して、すべてのHTTPメソッドのWebサービスを使用できます。 以下に示すコードは、RESTテンプレートのBeanを作成して、RESTテンプレートオブジェクトを自動配線する方法を示しています。

package com.finddevguides.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class DemoApplication {
   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
   @Bean
   public RestTemplate getRestTemplate() {
      return new RestTemplate();
   }
}

GET

  • RESTTemplate-exchange()メソッドを使用してGET APIを使用する *

このURL* http://localhost:8080/products *は次のJSONを返し、次のコードを使用してRESTテンプレートを使用してこのAPI応答を使用すると想定します-

[
   {
      "id": "1",
      "name": "Honey"
   },
   {
      "id": "2",
      "name": "Almond"
   }
]

APIを使用するには、指定されたポイントに従う必要があります-

  • Restテンプレートオブジェクトを自動配線しました。
  • HttpHeadersを使用して、リクエストヘッダーを設定します。
  • HttpEntityを使用して、要求オブジェクトをラップします。
  • Exchange()メソッドのURL、HttpMethod、およびReturn型を指定します。
@RestController
public class ConsumeWebService {
   @Autowired
   RestTemplate restTemplate;

   @RequestMapping(value = "/template/products")
   public String getProductList() {
      HttpHeaders headers = new HttpHeaders();
      headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
      HttpEntity <String> entity = new HttpEntity<String>(headers);

      return restTemplate.exchange("
         http://localhost:8080/products", HttpMethod.GET, entity, String.class).getBody();
   }
}

POST

  • RestTemplateを使用したPOST APIの使用-exchange()メソッド *

このURL* http://localhost:8080/products *が以下に示す応答を返すと想定します。Restテンプレートを使用してこのAPI応答を使用します。

以下に示すコードは、リクエストの本文です-

{
   "id":"3",
   "name":"Ginger"
}

以下に示すコードは、応答本文です-

Product is created successfully

APIを使用するには、以下のポイントに従う必要があります-

  • Restテンプレートオブジェクトを自動配線しました。
  • HttpHeadersを使用して、リクエストヘッダーを設定します。
  • HttpEntityを使用して、要求オブジェクトをラップします。 ここでは、Productオブジェクトをラップしてリクエスト本文に送信します。
  • exchange()メソッドのURL、HttpMethod、およびReturn型を指定します。
@RestController
public class ConsumeWebService {
   @Autowired
   RestTemplate restTemplate;

   @RequestMapping(value = "/template/products", method = RequestMethod.POST)
   public String createProducts(@RequestBody Product product) {
      HttpHeaders headers = new HttpHeaders();
      headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
      HttpEntity<Product> entity = new HttpEntity<Product>(product,headers);

      return restTemplate.exchange(
         "http://localhost:8080/products", HttpMethod.POST, entity, String.class).getBody();
   }
}

PUT

  • RestTemplateを使用したPUT APIの使用-exchange()メソッド *

このURL* http://localhost:8080/products/3 *が以下の応答を返し、Rest Templateを使用してこのAPI応答を使用すると仮定します。

以下に示すコードはリクエスト本文です-

{
   "name":"Indian Ginger"
}

以下に示すコードは、応答本文です-

Product is updated successfully

APIを使用するには、以下のポイントに従う必要があります-

  • Restテンプレートオブジェクトを自動配線しました。
  • HttpHeadersを使用して、リクエストヘッダーを設定します。
  • HttpEntityを使用して、要求オブジェクトをラップします。 ここでは、Productオブジェクトをラップしてリクエスト本文に送信します。
  • exchange()メソッドのURL、HttpMethod、およびReturn型を指定します。
@RestController
public class ConsumeWebService {
   @Autowired
   RestTemplate restTemplate;

   @RequestMapping(value = "/template/products/{id}", method = RequestMethod.PUT)
   public String updateProduct(@PathVariable("id") String id, @RequestBody Product product) {
      HttpHeaders headers = new HttpHeaders();
      headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
      HttpEntity<Product> entity = new HttpEntity<Product>(product,headers);

      return restTemplate.exchange(
         "http://localhost:8080/products/"+id, HttpMethod.PUT, entity, String.class).getBody();
   }
}

DELETE

  • RestTemplateを使用したDELETE APIの使用-exchange()メソッド *

このURL* http://localhost:8080/products/3 *が以下に示す応答を返し、Rest Templateを使用してこのAPI応答を使用すると仮定します。

以下に示すコードのこの行は、応答本文です-

Product is deleted successfully

APIを使用するには、以下に示すポイントに従う必要があります-

  • Restテンプレートオブジェクトを自動配線しました。
  • HttpHeadersを使用して、リクエストヘッダーを設定します。
  • HttpEntityを使用して、要求オブジェクトをラップします。
  • exchange()メソッドのURL、HttpMethod、およびReturn型を指定します。
@RestController
public class ConsumeWebService {
   @Autowired
   RestTemplate restTemplate;

   @RequestMapping(value = "/template/products/{id}", method = RequestMethod.DELETE)
   public String deleteProduct(@PathVariable("id") String id) {
      HttpHeaders headers = new HttpHeaders();
      headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
      HttpEntity<Product> entity = new HttpEntity<Product>(headers);

      return restTemplate.exchange(
         "http://localhost:8080/products/"+id, HttpMethod.DELETE, entity, String.class).getBody();
   }
}

完全なRest Template Controllerクラスファイルは以下のとおりです-

package com.finddevguides.demo.controller;

import java.util.Arrays;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.finddevguides.demo.model.Product;

@RestController
public class ConsumeWebService {
   @Autowired
   RestTemplate restTemplate;

   @RequestMapping(value = "/template/products")
   public String getProductList() {
      HttpHeaders headers = new HttpHeaders();
      headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
      HttpEntity<String> entity = new HttpEntity<String>(headers);

      return restTemplate.exchange(
         "http://localhost:8080/products", HttpMethod.GET, entity, String.class).getBody();
   }
   @RequestMapping(value = "/template/products", method = RequestMethod.POST)
   public String createProducts(@RequestBody Product product) {
      HttpHeaders headers = new HttpHeaders();
      headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
      HttpEntity<Product> entity = new HttpEntity<Product>(product,headers);

      return restTemplate.exchange(
         "http://localhost:8080/products", HttpMethod.POST, entity, String.class).getBody();
   }
   @RequestMapping(value = "/template/products/{id}", method = RequestMethod.PUT)
   public String updateProduct(@PathVariable("id") String id, @RequestBody Product product) {
      HttpHeaders headers = new HttpHeaders();
      headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
      HttpEntity<Product> entity = new HttpEntity<Product>(product,headers);

      return restTemplate.exchange(
         "http://localhost:8080/products/"+id, HttpMethod.PUT, entity, String.class).getBody();
   }
   @RequestMapping(value = "/template/products/{id}", method = RequestMethod.DELETE)
   public String deleteProduct(@PathVariable("id") String id) {
      HttpHeaders headers = new HttpHeaders();
      headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
      HttpEntity<Product> entity = new HttpEntity<Product>(headers);

      return restTemplate.exchange(
         "http://localhost:8080/products/"+id, HttpMethod.DELETE, entity, String.class).getBody();
   }
}

Spring Boot Application Classのコード-DemoApplication.javaは以下のとおりです-

package com.finddevguides.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {
   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
}

Mavenビルドのコード– pom.xmlは以下のとおりです-

<?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.finddevguides</groupId>
   <artifactId>demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>demo</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.8.RELEASE</version>
      <relativePath/>
   </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-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>

Gradle Buildのコード– build.gradleを以下に示します-

buildscript {
   ext {
      springBootVersion = '1.5.8.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.finddevguides'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
dependencies {
   compile('org.springframework.boot:spring-boot-starter-web')
   testCompile('org.springframework.boot:spring-boot-starter-test')
}

次のMavenまたはGradleコマンドを使用して、実行可能なJARファイルを作成し、Spring Bootアプリケーションを実行できます-

Mavenの場合、以下に示すコマンドを使用できます-

mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleの場合、以下に示すコマンドを使用できます-

gradle clean build

「BUILD SUCCESSFUL」の後に、build/libsディレクトリの下にJARファイルがあります。

今、次のコマンドを使用してJARファイルを実行します-

java –jar <JARFILE>

これで、アプリケーションはTomcatポート8080で開始されました。

Tomcat Port_8080で開始されたアプリケーション

次に、POSTMANアプリケーションで以下のURLにアクセスすると、出力を確認できます。

Restテンプレートによる製品の取得- http://localhost:8080/template/products

RESTテンプレートで製品を取得

製品の作成POST- http://localhost:8080/template/products

製品POSTの作成

製品PUTの更新- http://localhost:8080/template/products/3

製品の更新POST

製品の削除- http://localhost:8080/template/products/3

商品の削除POST