Documentation

You are viewing the documentation for the 2.2.0 release in the 2.2.x series of releases. The latest stable release series is 2.4.x.

§Play WS API

ときどき、Play アプリケーションから他の HTTP サービスを呼び出したくなることがあります。そんなときは、 Play が提供している、非同期 HTTP 呼び出しを行うためのライブラリ play.libs.WS を使いましょう。

play.libs.WS による HTTP 呼び出しは、あとから Play の非同期メカニズムを使って操作することのできる Promise<WS.Response> を返します。

§インポート

WS クラスを使うためには、まず以下のパッケージをインポートします:

import play.libs.WS;
import play.mvc.Result;

import static play.libs.F.Function;
import static play.libs.F.Promise;

§HTTP 呼び出しを作成する

HTTP リクエストを作成するためには、まず WS.url() で URL を指定します。その結果、例えばヘッダをセットする、といったような 各種 HTTP オプションを指定するためのビルダが返ってきます。オプションの指定が終わったら、最後に利用したい HTTP メソッドに対応するメソッドを呼び出します。例を挙げると、

Promise<WS.Response> homePage = WS.url("http://example.com").get();

または、以下のように記述します。

Promise<WS.Response> result = WS.url("http://example.com").post("content");

§リカバリ

透過的な呼び出しにおけるエラーからリカバリしたい場合は、レスポンスの代わりに recover を使うことができます。

Promise<WS.Response> callWithRecover = homePage.recover(new Function<Throwable, WS.Response>() {
    @Override
    public WS.Response apply(Throwable throwable) throws Throwable {
        return WS.url("http://backup.example.com").get().get(timeout);
    }
});

§HTTP レスポンスを取得する

HTTP 呼び出しは非同期で行われ、実際のコンテンツを取得するためには Promise<WS.Response> を操作する必要があります。また、複数の Promise を合成して、最終的に Play サーバが直接的に処理できるように Promise<Result> を返す、という方法も使えます。

public static Promise<Result> index() {
    final Promise<Result> resultPromise = WS.url(feedUrl).get().map(
            new Function<WS.Response, Result>() {
                public Result apply(WS.Response response) {
                    return ok("Feed title:" + response.asJson().findPath("title"));
                }
            }
    );
    return resultPromise;
}

§結果を合成する

複数の HTTP 呼び出しを順番に行いたい場合は、 flatMap を使うとよいでしょう。

public static Promise<Result> index() {
    final Promise<Result> resultPromise = WS.url(feedUrl).get().flatMap(
            new Function<WS.Response, Promise<Result>>() {
                public Promise<Result> apply(WS.Response response) {
                    return WS.url(response.asJson().findPath("commentsUrl").asText()).get().map(
                            new Function<WS.Response, Result>() {
                                public Result apply(WS.Response response) {
                                    return ok("Number of comments: " + response.asJson().findPath("count").asInt());
                                }
                            }
                    );
                }
            }
    );
    return resultPromise;
}

§HTTP クライアントを設定する

Play アプリケーション全体で使われる HTTP クライアントの設定は、 application.conf にほんの少しプロパティを設定するだけで行えます。

# Follow redirects (default true)
ws.followRedirects=true
# Connection timeout in ms (default 120000)
ws.timeout=120000
# Whether to use http.proxy* JVM system properties (default true)
ws.useProxyProperties=true
# A user agent string to set on each request (default none)
ws.useragent="My Play Application"

次ページ: Akka との統合