使用Java Play发送HTTP请求(WSClient初始化)

时间:2017-07-11 11:04:52

标签: java sockets playframework playframework-2.0

我从定义客户端类的官方Play 2.6文档中获取以下代码,

import javax.inject.Inject;
import play.libs.ws.*;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.CompletionStage;

public class MyClient implements WSBodyReadables, WSBodyWritables {
    private WSClient ws;

    @Inject
    public MyClient(WSClient ws) {
        this.ws = ws;
        sendRequest();
    }

    public void sendRequest() {
        WSRequest request = ws.url("http://example.com");

        WSRequest complexRequest = request.addHeader("headerKey", "headerValue")
                .setRequestTimeout(Duration.of(1000, ChronoUnit.MILLIS))
                .addQueryParameter("paramKey", "paramValue");

        CompletionStage<? extends WSResponse> responsePromise = complexRequest.get();
    }
}

现在我有一个处理传入套接字消息的套接字actor。我想在每次通过套接字发送新消息时触发HTTP请求。

我的问题是我不知道如何初始化MyClient类以使用其sendRequest方法。

public void onReceive(Object message) throws Exception {
    if (message instanceof String) {
        out.tell("I received your message: " + message, self());
        MyClient a = new MyClient(); //problem here
    }
}

1 个答案:

答案 0 :(得分:1)

你必须注射它,就像你在MyClass中所做的那样:

public class MyActor extends UntypedAbstractActor {

    private MyClient client;

    @Inject
    public MyActor(MyClient client) {
        this.client = client;
    }

    @Override
    public void onReceive(Object message) throws Exception {
        client.sendRequest();
    }
}

如果有一些问题不允许你使用它(例如,你不控制演员的创建方式),请在你的问题中添加更多信息。