Play WSは、Play Frameworkで使用するためにもともとPlayチームによって開発された強力なHTTPクライアントライブラリです。 HTTPクライアント機能にasynchttpclientを使用し、再生依存関係はありません。
ここでは、アプリでPlay WSを使用する方法(プレイなし)についていくつかのドキュメントを提供しました。プレイでPlay WSの使用方法の詳細については、Play Documentationを参照してください。
開始するために、SBTの依存関係としてplay-ahc-ws-standalone
を追加できます。
Library-dependencies += "org.playframework" %% "play-ahc-ws-standalone"% "rist_version" //バージョン3.0.0:library-dependencies += "com.typesafe.play" %% "play-ahc-ws-スタンドアロン「%」最新_ version "
LATEST_VERSION
versionをこの画像に示すバージョンに置き換えます。
これにより、AsynchttpClientに裏付けられたPlay WSのスタンドアロンバージョンが追加されます。 このライブラリにはplay.libs.ws
ScalaとJava APIの両方が含まれplay.api.libs.ws
います。
Play-JSONまたはScala XMLを使用してXMLおよびJSONサポートを追加するには、以下を追加します。
Library-dependencies += "org.playframework" %% "play-ws-standalone-xml"%playwsstandaloneversion Library-dependencies += "org.playframework" %% "play-ws-standalone-json"%playwsstandaloneversion //バージョン3.0.0:com.typesafe.play "%%" play-ws-standalone-xml " %PlaywsstandalOneversion Library-dependencies += "com.typesafe.play" %% "play-ws-standalone-json"%playwsstandaloneversion
Play WSは、 play.shaded.ahc
とplay.shaded.oauth
パッケージ名の下でそれぞれ再パッケージ化された、asynchttpclientとoauthのsignpostの影付きバージョンを使用します。 シェーディングasynchttpclientとは、asynchttpclientの背後で使用されるnettyのバージョンがアプリケーションとプレイ全体に完全に独立していることを意味します。
具体的には、シェーディングAsynchttpClientは、Play WSを使用してNetty 4.0とNetty 4.1の間に導入されたバージョンの競合が導入されていないことを意味します。
注:
sbt publishLocal
を使用してPlay-WSを開発し、shaded-asynchttpclient
とshaded-oauth
公開している場合は、~/.ivy2/local
更新が~/.ivy2/cache
を上書きしないため、表示されないことに注意する必要があります。キャッシュから削除するまで、更新されたシェードコード。 詳細については、http://eed3si9n.com/field-testを参照してください。 このバグは、SBT/SBT#2687として提出されました。
WSシェードasynchttpclientを再生するため、デフォルトの設定も網掛けされているため、AHCドキュメントを順守しないでください。 これはahc-default.properties
およびusePooledMemory
システムのプロパティの設定がplay.shaded.ahc
で準備されていることを意味します。
play.shaded.ahc.org.asynchttpclient.usepooledmemory = true
Play-WSのタイプシステムが変更されたため、リクエスト本体と応答本体がより豊かなタイプを使用できるようになりました。
独自のBodyWritableまたはBodyReadableを定義できますが、ボックスからデフォルトの設定を使用する場合は、defaultboydedeadables / defaultbodybodywritablesでタイプマッピングをインポートできます。
play.api.libs.ws.defaultbodyreadables._import play.api.libs.ws.defaultbodywritables._
XMLとJSONのサポートが必要になる可能性が高くなります。
play.api.libs.ws.xmlbodyreadables._import play.api.libs.ws.xmlbodywritables._
または
play.api.libs.ws.jsonbodyreadables._import play.api.libs.ws.jsonbodywritables._
応答でBodyReadableを使用するには、応答を明示的に入力する必要があります。
Scala.concurrentをインポート。{executionContext、future} import play.api.api.libs.ws.standalonewsclientimport play.api.api.libs.ws.xmlbodyreadables._ // rebusedef handlexml(ws:standalonewsclient)(inclicteccontext):executioncontext:future [scala .xml.elem] = ws.url( "...")。get()。map {response => respons.body [scala.xml.elem] }
またはPlay-jsonを使用してください:
Scala.concurrentをインポートします。{executionContext、Future} import play.api.libs.json.jsvalueimport play.api.libs.ws.standalonewsclientimport play.api.libs.ws.jsonbodyreadables._ //必須デフハンドルJsonresp(ws:standalonewsclient)(standalonewsclient)(ws)暗黙のEC:executionContext):Future [jsvalue] = ws.url( "...")。get()。map {response => respons.body [jsvalue] }
特別なケースがあることに注意してください。応答をストリーミングしているときは、情報源として身体を取得する必要があります。
scala.concurrent.executioncontextimport org.apache.pekko.util.bytestringimport org.apache.pekko.stream.sourceimport play.api.api.libs.wstandalonewsclientdef usewsstream(ws:standalonewsclictext)(executingclictext:executingctream) ws.url( "...")。stream()。map {response => val source:source [bytestring、_] = response.bodyassource val _ = source //ソースで何かを行う }
投稿するには、BodyWritableの暗黙のクラスマッピングがあるタイプを渡す必要があります。
scala.concurrent.executioncontextimport play.api.libs.ws.defaultbodywritables._ //必要なdef postexamplestring(ws:play.api.libs.ws.standalonewsclient)(暗黙のec:executioncontext)= {val stringa = "hello world" ws.url( "...")。post(stringdata).map {response => / *何か * /} }
また、独自のカスタムボディレディーブルを定義することもできます。
import play.api.api.libs.ws.bodyreadableimport play.api.libs.ws.ahc.standaloneahcwsresponsecase class foo(body:string)暗黙のval foobodyreadable = bodyreadable [foo] {respons =>>>> import play.haded.ahc.org.asynchttpclient。{response => ahcresponse} val ahcreSponse = response.asinstanceof [standaloneahcwsresponse] .underlying [ahcresponse] foo(ahcresponse.getResponseBody) }
またはカスタムボディライター:
org.apache.pekko.util.bytestringimport play.api.libs.ws. {bodywritable、inmemorybody}暗黙のval writeable of_foo:bodywritable [foo] = {// https://tools.ietf.org/html/rfc6838#section -3.2 bodywritable(foo => inmemorybody(bytestring.fromstring(foo.tostring))、 "application/vnd.company.category+foo") }
Javaでデフォルトのタイプマッピングを使用するには、以下を使用する必要があります。
import play.libs.ws.defaultbodyreadables; import play.libs.ws.defaultbodywritables;
に続く:
パブリッククラスMyClient Implesments DefaultBodyWritables、DefaultBodyDeadables {public ReftionStage <String> dostuff(){return Client.url( "http://example.com").post(body( "hello world"))。 .body(string()) ); } }
特別なケースがあることに注意してください。ストリームを使用している場合は、ソースとして体を取得する必要があります。
class myclass {public recompletStage <source <bytestring、notused >> readResponseasStream(){return ws.url(url).stream()。thnapply(respons-> respons.bodyassource() ); } }
ソースを投稿することもできます。
class myclass {public refterment -stage <string> dostuff(){source <bytestring、notused> source = fromsource(); return ws.url(url).post(body(source))。 ); } }
カスタムBodyReadable
ものを定義できます。
import play.libs.ws.ahc。*; import play.shaded.ahc.org.asynchttpclient.response; class fooreadable emplence bodyreadable <standalonewsresponse、foo> {public foo apply(standalonewsresponse response){response ahcresponse =(応答)応答。 getUnderlying(); return foo.serialize(ahcreSponse.getResponseBody(StandardCharsets.utf_8)); } }
また、独自のカスタムBodyWritable
を定義することもできます。
パブリッククラスmyClient {private bodywritable <string> sotermethod(string string){org.apache.pekko.util.bytestring bytestring = org.apache.pekko.util.bytestring.fromstring(string); 新しいdefaultbodybodywritables.inmemorybodywritable(bytestring、 "text/plain")を返します。 } }
スタンドアロンのクライアントは、ストリーミングデータを内部的に処理するためにPEKKOが必要です。
Scalaでは、Webサービスに電話をかけ、クライアントを閉鎖する方法:
playwsclientimport org.apache.pekko.actor.actor.pekko.pekko.stream._import play.api.libs.ws.ws.ws.ws.ws.ws.ws.ws.ws.api.libs.ws.ahc._import scala.concurrent.futureobjectlient {defaul defalybodedables。 _ scala.concurrent.executioncontext.implicits._インポート def main(args:array [string]):unit = {//スレッドおよびストリーミングのためのPEKKOシステムを作成してください。 system.registerontermination {system.exit(0) } Implical Val Materalizer = SystemMaterializer(system).Materializer //スタンドアロンWSクライアント//作成されない引数は、// "AHCWSCLIENTCONFIGFACTORY.FORCONFIG(configactory.load、this.getclass.getclassoloader)から作成されたAHCWSCLIENTCONFIGのデフォルトをデフォルトしません。 () 電話(wsclient) 。 。 } def call(wsclient:standalonewsclient):future [unit] = { wsclient.url( "http://www.google.com").get()。マップ{response => val statustext:string = respons.statustext val body = respons.body [string] println(s "Response A $ statustext:$ body")) } } }
また、asynchttpclientインスタンスからスタンドアロンクライアントを直接作成することもできます。
Object scalaclient {def main(args:array [string]):unit = {// import play.shaded.ahc.asynchttpclient._val asynchttpclientconfig = new defaultasynchttpclientconfig.builder() .setMaxRequestretry(0) .setshutdownquetperiod(0) .setShutDownTimeout(0).Buildval AsynchttpClient = new DefaultAsynchttpClient(asynchttpclientconfig)val wsclient = new Standaloneahcwsclient(asynchttpclient)/// ... } }
これは、WS構成レイヤーでは使用できないAsynchttpClient構成オプションがある場合に役立ちます。
Javaでは、APIはほとんど同じです:
パッケージplaywsclient; Import org.apache.pekko.actor.actorsystem; Import org.apache.pekko.stream。*; import com.typesafe.config.configfactory; import play.libs.ws。*; Import Play.libs.ws. AHC。*;パブリッククラスJavaclientを実装しているDefaultBodyDeadables {private final standaloneahcwsclientクライアント;プライベート最終的なActorsystem System; public static void main(String [] args){// PEKKO Materalizerを設定してストリーミングファイナル文字列名= "WSCLIENTシステム=" WSCLIENTシステム= actorsystem.create(name); system.registerontermination(() - > system.exit(0)); gatergleizer gatherizer = systemmaterializer.get(system).materializer(); // `application.conf`からwsクライアントを作成します。ファイル、現在のクラスローダー、およびMaterializer.standaloneahcwsclient ws = standaloneahcwsclient.create(ahcwsclientconfigfactory.forconfig(configactory.load()、system.getclass()。 javaclient.run(); } javaclient(Actorsystem System、StandAloneAhcwsClient Client){this.system = system; this.client = client; } public void run(){client.url( "http://www.google.com").get() .whenComplete((response、throwable) - > {string statustext = respons.getStatustext(); string body = response.getBody(string()); system.out.println( "reass" + statustext); }) .thenrun(() - > {try {client.close(); } catch(Exception e){e.printstacktrace(); } }) .thenrun(system :: terminate); } }
同様に、構成からasynchttpclientクライアントを明示的に提供できます。
パブリッククラスJavaClient Implesments DefaultBodyReadables {public static void main(String [] args){// ... // configasynchttpclientconfig asynchttpclientconfig = new defaultasynchttpclientconfig.builder( .setMaxRequestretry(0) .setshutdownquetperiod(0) .setshutdowntimeout(0) .build(); asynchttpclient asynchttpclient = new DefaultAsynchttpClient(asynchttpclientconfig); // asynchttpclientから直接wsclientインスタンスを設定します。wsclientclient = new ahcwsclient(asynchttpclient、materalizer); // ...} }
WSを再生し、SCALAの最小限のHTTPキャッシュ管理ライブラリであるCachingAsynchttpClient、Ahchttpcache、およびCachecontrolを介してHTTPキャッシュを実装します。
キャッシュを使用するスタンドアロンAHCクライアントを作成するには、基礎となる実装にキャッシュアダプターを使用してAhchttpcacheのインスタンスを渡します。 たとえば、カフェインを基礎となるキャッシュとして使用するには、以下を使用できます。
import scala.concurrent.Futureimport java.util.concurrent.TimeUnitimport com.github.benmanes.caffeine.cache.{ Caffeine, Ticker }import play.api.libs.ws.ahc.StandaloneAhcWSClientimport play.api.libs.ws.ahc. cache。{ahchttpcache、cache、effectionurikey、responseentry} class caffeinehttpcache extends cache {val bushenting = caffeine.newbuilder() .ticker(ticker.systemticker()) .expireafterwrite(365、timeunit.days) .build [effectionurikey、responseentry]()def remover(key:efferencyurikey)= future.successful(option.invalidate(key)))def(key:effectionurikey、entry:responseentry)= future.succesfly(butylying.put( (key、entry))def get(key:effectionurikey)= future.successful(option(基礎となるgetifpresent key))def close():unit = rundlying.cleanup() } def withcache(Implict M:org.apache.pekko.stream.materializer):standaloneahcwsclient = {inclicit def ec = m.executionContext val cache = new caffeinehttpcache()standaloneahcwsclient(httpcache = our(httpcache(cache))) }
キャッシュコントロールヘッダーをまとめるのに役立つ多くのガイドがあります。
HTTPキャッシングに関するMozillaのガイド
キャッシュに関するノッティンガムのガイド
HTTPキャッシュ
安らぎ:HTTPキャッシュ
https://github.com/playframework/.github/blob/main/releasing.mdを参照してください
Play WSは、Apacheライセンス、バージョン2に基づいてライセンスされています。詳細については、ライセンスファイルを参照してください。