5

シンプルな Jersey クライアントを作成しましたが、ペイロードを使用して POST 要求を正常に実行できます。しかし、今は http エンドポイントからの応答を待っています。

public void callEndpoint(String endpoint, String payload) {

    try {
        ClientConfig config = new DefaultClientConfig();
        Client client = Client.create(config);
        WebResource webResource = client.resource(getBaseURI(endpoint));

        log.debug("Sending payload [" + payload + "] to URL - [" + getBaseURI(endpoint) + "]");

        // POST method - Is this blocking?
        // Is it possible to not wait for response here
        ClientResponse response = webResource.accept("application/json")
                                             .type("application/json")
                                             .post(ClientResponse.class, payload);
        if (response.getStatus() != 200) {
            log.error("The endpoint [" + getBaseURI(endpoint) + "] returned a non 200 status code [" + response.getStatus() + "] ");
        }

    } catch (Exception e) {
        log.error("The endpoint for " + endpoint + " - " + getBaseURI(endpoint) + " is not reachable. This is the exception - " + e);
    }

}

private URI getBaseURI(String endpoint) {
    // Get this URI from config
    String URL = "http://www.somewhere.com/v2/" + endpoint;
    return UriBuilder.fromUri(URL).build();
}

質問: コードが応答を待たない可能性はありますか?

コードが応答を待たない可能性があるかどうかを確認するために、 Jersey クライアントのドキュメントを読み込もうとしていました。応答を読み取ってからしか接続を閉じることができないことがわかりましたが、私の場合は役に立ちません。エンドポイントにペイロードを投稿したらすぐに接続を閉じたいです。

応答を気にしないので、POST 要求を起動して忘れる必要があります。これは、そのエンドポイントでの処理に多くの時間がかかり、スレッドが処理を待機したくないためです。

また、すべてではなく一部のリクエストに対する応答を待つことは可能ですか? クライアントを待機させる/待機させないように設定できるパラメーターはありますか? 私はまだJavaドキュメントを読んでいるので、これは非常に単純な設定かもしれませんが、今まで見つけることができなかったので、ここで尋ねます. ありがとう!

[アップデート]

次のコードで動作しましたが、Java サンプル コードを実行すると、すぐに開始と完了が出力されますが、プログラムはしばらく実行され続けてから終了します。将来の応答を待っていると推測しているので、スクリプトを待たないようにすることは可能ですか? コードは次のとおりです。

public static void callEndpoint(String endpoint, String payload) {

    try {
        ClientConfig config = new DefaultClientConfig();
        Client client = Client.create(config);
        AsyncWebResource webResource = client.asyncResource(getBaseURI(endpoint));

        // POST method
        System.out.println("start");
        Future<ClientResponse> resp = webResource.accept("application/json")
                .type("application/json")
                .post(ClientResponse.class, payload);
        // This line makes the code wait for output
        //System.out.println(resp.get()); 

    } catch (Exception e) {

        System.out.println ("The endpoint for " + endpoint + " - " + getBaseURI(endpoint) + " is not reachable. This is the exception - " + e);
    }
    System.out.println("done");
}
4

2 に答える 2