Spring Boot の RestTemplate
を使って、Basic認証が必要な外部サービスにアクセスする方法を書いていきます。
バージョン
- Spring Boot 2.7.5
1. pom.xml の作成
Maven の定義を作成します。spring-boot-starter-web
を使うように設定すれば、他のビルドシステムでも大丈夫です。
pom.xml
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.5</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>org.sample</groupId> <artifactId>spring-resttemplate</artifactId> <version>0.0.1</version> <properties> <java.version>17</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>
2. コードの作成
Java のプログラムの例は以下の通りです。
src/main/java/org/sample/Main.java
package org.sample; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; import java.util.Base64; public class Main { public static void main(String[] args) { // Basic認証のヘッダー情報を作成 String userPassword = new String( Base64.getEncoder().encode( "ユーザー名:パスワード".getBytes() ) ); StringBuilder basicAuth = new StringBuilder(); basicAuth.append("Basic ").append(userPassword); HttpHeaders headers = new HttpHeaders(); headers.add("Authorization", basicAuth.toString()); // 外部サービスにアクセス RestTemplate client = new RestTemplate(); HttpEntity<String> req = new HttpEntity<>(headers); ResponseEntity<String> res = client.exchange( "リクエストURL", HttpMethod.GET, req, String.class ); // レスポンスを標準出力 System.out.println(res.getBody()); } }
上の二重引用符内の
- ユーザー名
- パスワード
- リクエストURL
を置き換えて頂ければアクセスできます。
ユーザー名とパスワードの区切り文字 :
は必要になります。