使用Java Play发送HTTP请求(WSClient初始化)
下面的代码取自定义客户端类的官方Play 2.6文档使用Java Play发送HTTP请求(WSClient初始化),java,sockets,playframework,playframework-2.0,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, WSBodyWrita
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();
}
}
必须注入它,就像在MyClass中一样:
如果有一些问题不允许您使用此ex,您无法控制演员的创建方式,请在您的问题中添加更多信息。之前,我是这样实例化MyActor的:return WebSocket.Text.acceptrequest->ActorFlow.actorRefMyActor::props,actorSystem,materializer;这已经不起作用了,那么我该怎么做呢?然后我想你可以在创建actor时注入Cyclient对象,然后不用MyActor::props,而是使用props.createMyActor.class,即\u MYCLIENT的\u注入的\u实例。
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
}
}
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();
}
}