RESTEasyのメモ。
RESTEasyは、RESTfulなウェブサービスにアクセスするクライアントを作るためのライブラリー。
WildFly(JBossのOSS版)で使われている。
plugins {
id 'java'
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
}
}
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.jboss.resteasy:resteasy-client:6.2.7.Final'
}
import jakarta.ws.rs.client.Client; import jakarta.ws.rs.client.ClientBuilder; import jakarta.ws.rs.client.WebTarget;
public class RestClientMain {
public static void main(String... args) {
try (Client client = ClientBuilder.newClient()) {
WebTarget target = client.target("http://localhost:8080/base/api/resource1");
// WebTarget target = client.target("http://localhost:8080/base").path("/api").path("/resource1");
// WebTarget target = client.target("http://localhost:8080/base").path("api").path("resource1");
String result = target.request().get(String.class);
System.out.println(result);
}
}
}
HTTPリクエストのGETの場合、request()のgetメソッドを呼ぶ。
getメソッドの引数には、取得したいデータ型(クラス)を渡す。
request.get()(引数なし)だとResponseが返る。
この場合はステータス等も取れる。
import jakarta.ws.rs.core.Response;
Response response = target.request().get();
System.out.println(response.getStatus());
String result = response.readEntity(String.class);
System.out.println(result);