5

For Play 2.3.X the WS module is very easy to be used:

WS.url(s"http://$webEndpoint/hand/$handnumber").get()

For the such simple and strightforward usage.

While in Play 2.6.x according to the link : https://www.playframework.com/documentation/2.6.x/JavaWS You need to create a http client firstly.

WSClient customWSClient = play.libs.ws.ahc.AhcWSClient.create(
    play.libs.ws.ahc.AhcWSClientConfigFactory.forConfig(
            configuration.underlying(),
            environment.classLoader()),
            null, // no HTTP caching
            materializer);

And what's more, you also need a materializer and an akka system to support the materializer.

String name = "wsclient";
ActorSystem system = ActorSystem.create(name);
ActorMaterializerSettings settings =       ActorMaterializerSettings.create(system);
ActorMaterializer materializer = ActorMaterializer.create(settings, system, name);
// Set up AsyncHttpClient directly from config
AsyncHttpClientConfig asyncHttpClientConfig = new  DefaultAsyncHttpClientConfig.Builder()
    .setMaxRequestRetry(0)
    .setShutdownQuietPeriod(0)
    .setShutdownTimeout(0).build();
AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient(asyncHttpClientConfig);

// Set up WSClient instance directly from asynchttpclient.
WSClient client = new AhcWSClient(
asyncHttpClient,
materializer

);

I knew it will add more features to the WS client, but when I just want a simple http client, the usage become unaccept complex, it's so wired.

4

3 回答 3

5

您链接到的页面说:

我们建议您使用上述依赖注入获取 WSClient 实例。通过依赖注入创建的 WSClient 实例使用起来更简单,因为它们会在应用程序启动时自动创建,并在应用程序停止时清理。

WSClient手动创建实例是乏味的也就不足为奇了。

并且同一页面描述了如何使用注入版本WSClient

import javax.inject.Inject;

import play.mvc.*;
import play.libs.ws.*;
import java.util.concurrent.CompletionStage;

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

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

这和以前的版本一样简单。实际上,在以前的 Play 版本中,您也可以创建自定义实例WSClient, 并且过去具有相当的复杂性(模 Akka 的东西)。

于 2017-10-11T08:23:16.150 回答
1

最后我使用ScalaJ-http,https://github.com/scalaj/scalaj-http

这很容易使用:

import scalaj.http._
...
response= Http("http://localhost:5000/health").asString

这很简单,就像游戏中的 WS 2.3.6

对于 Play 2.6.x,框架可能不会为您创建默认 ws,请参阅https://github.com/playframework/play-scala-tls-example/blob/2.6.x/app/Main.scala的示例

于 2017-10-11T13:24:29.770 回答
0

对于使用完全 DI 支持的 Scala Play 的人来说,创建 WSClient 实例的一种解决方案是Play.current.injector.instanceOf[WSClient]. 这在更新到 Scala Play 2.6 时也很有用,只需稍作改动而不向所有人添加 DI 支持。

于 2018-09-20T11:19:30.020 回答