Play WS是一個功能強大的HTTP客戶庫庫,最初是由Play團隊開發的,可與Play Framework一起使用。它將AsynchttpClient用於HTTP客戶端功能,並且沒有播放依賴性。
我們在此處提供了一些有關如何在您的應用中使用play ws的文檔(無需播放)。有關如何在遊戲中使用WS的更多信息,請參閱播放文檔。
首先,您可以將play-ahc-ws-standalone
添加為SBT中的依賴性:
libraryDepentencies +=“ org.playframework” %%” play-ahc-ws-standalone“%”最新_version“ //版本3.0.0:libraryDeppedencies +=” com.typesafe.play.play;獨立的“%”最新_version”
在此圖像中顯示的版本中,您可以在其中替換LATEST_VERSION
:。
這添加了Play WS的獨立版本,並由Asynchttpclient支持。 該庫在play.api.libs.ws
和play.libs.ws
下同時包含Scala和Java Apis。
要使用Play-Json或Scala XML添加XML和JSON支持,請添加以下內容:
library Dippedies +=“ org.playframework” %%” play-ws-standalone-xml”%playwsstandaloneversion library Dippentencies +=“ org.playframework” %%” play-ws-standalone-json“%playwsstandaloneversion //版本3.0.0:libraryDeppentendencies +=“ com.typesafe.play” %% play-ws-ws-sandalone-antalone -xmml“ com.typesafe.play” %playwsstandaloneversion library Depentencies +=“ com.typesafe.play“ %%” play-ws-standalone-json“%playwsstandaloneversion
Play WS使用play.shaded.ahc
和Oauth標誌的陰影版本,分別play.shaded.oauth
包裝。 陰影asynchttpclient意味著,在AsynchttpClient背後使用的Netty版本完全獨立於應用程序,並且整體上播放。
具體而言,陰影asynchttpclient意味著使用play ws之間沒有任何版本衝突。
注意:如果您使用
sbt publishLocal
開發play-ws並發布shaded-asynchttpclient
和shaded-oauth
,則需要意識到更新~/.ivy2/local
不會覆蓋~/.ivy2/cache
,因此您看不到看到您更新的陰影代碼,直到將其從緩存中刪除為止。 有關更多詳細信息,請參見http://eed3si9n.com/field-test。 此錯誤已作為SBT/SBT#2687提交。
由於play ws shades asynchttpclient,因此默認設置也被陰影,因此不遵守AHC文檔。 這意味著ahc-default.properties
和usePooledMemory
System屬性中的設置與play.shaded.ahc
進行了驗證。
play.shaded.ahc.org.asynchttpclient.usepooledmemory = true
Play-WS中的類型系統已經改變,因此請求主體和響應主體可以使用更豐富的類型。
您可以定義自己的理事或理論可讀,但是如果要在框設置中使用默認值,則可以使用DefaultBody Rreadables / DefaultBodyWritobles導入類型映射。
導入play.api.libs.ws.defaultbody Readables._import Play.api.libs.ws.ws.defaultbodywritables._
您更有可能需要XML和JSON支持:
導入play.api.libs.ws.xmlBodyReadables._import Play.api.libs.ws.ws.xmlbodywritables._
或者
導入play.api.libs.ws.jsonbodyables._import Play.api.libs.ws.ws.jsonbodywritables._
要在響應中使用Bodyable可讀,您必須明確鍵入響應:
導入scala.concurrent。{executionContext,future} import play.api.libs.wsandalonewsclientimport play.api.libs.ws.ws.ws.ws.xmlbodreadables.__ // quilterdefhandlexml(ws:standalonewsclient) .xml.elem] = ws.Url(“ ...”)。get()。映射{wendesp => wendesp.body [scala.xml.elem] }
或使用Play-json:
導入scala.concurrent。{executionContext,future} import play.api.libs.json.jsvalueimport play.api.api.libs.ws.standalonewsalonewsclientimport play.api.libs.libs.ws.wsosonbodyables.__//隱式EC: executionContext):未來[JSvalue] = ws.Url(“ ...”)。get()。映射{wendesp => wendesp.body [jsvalue] }
請注意,有一種特殊情況:當您流式響應時,您應該將身體作為來源:
導入scala.concurrent.executionContextImport org.apache.pekko.util.bytestringimport org.apache.pekko.pekko.stream.scaladsl.sourceimport play.api.api.libs.ws.ws.ws.ws.w.sandalonewsalonewsalonewsalonewsalonewsalonewsclientdef usewsstream( ws.Url(“ ...”)。stream()。映射{worlds {wession => val source:source [bytestring,_] = response.bodysource val _ = source //對源 }
要發布,您應該通過一種具有隱性類映射的類型:
導入scala.concurrent.executionContextimport play.api.libs.ws.ws.defaultbodywritobles._ //必需的Deff postexamplestring(ws:play.api.libs.ws.wastalonewsclient) ws.url(“ ...”)。 }
您還可以定義自己的自定義物體可讀:
導入play.api.libs.wsobodyimport play.api.libs.ws.ws.ahc.standaloneahcwsresponsecase class foo(body:string)隱式val foobodyable = bodyable = bodyable = bodyable [foo] 導入play.shaded.ahc.org.asynchttpclient。{worlds => ahcresponse} val ahcresponse = response.asinstanceof [standaloneahcwsresponse]。 }
或自定義我的主題:
導入org.apache.pekko.util.bytestringimport play.api.libs.ws. {bodboltrable,bobswritable,inmemorybody}隱式val writabledof_foo:bosswrablets [foo] = {// -3.2 我的bossrtrable(foo => inmemorybody(bytestring.fromstring(foo.tostring)),“應用程序/vnd.company.category+foo”) }
要使用Java中的默認類型映射,您應該使用以下內容:
導入play.libs.ws.defaultbody Readables; import play.libs.ws.defaultbodywritobles;
其次是:
公共類myclient實施默認bodyWritables,defaultbody Readables {public plubly stage <string> dostuff(){return client.url(“ http://example.com”).post(body(body(hello hello world'hello world'' )。 .body(string()) ); } }
請注意,有一種特殊情況:當您使用流時,您應該將身體作為來源:
類myClass {public plubly stage <source <bytestring,notused >> readResponSeasStream(){return ws.url(url).stream()。 ); } }
您也可以發布一個來源:
類myclass {public plublionstage <string> dostuff(){source <bytestring,notused> source = fromSource(); return ws.url(url).post(body(source))。 ); } }
您可以定義自定義的BodyReadable
:
導入play.libs.ws.ahc。*; import play.shaded.ahc.org.asynchttpclient.response; class fooreadable實現bodyablesable <standalOnewsresponse,foo> {public foo applion applion(standalOnewsresponse ponsection(standalOnewsresponse響應響應){響應ahcresponse = (響應)響應。 getunderlying(); return foo.serialize(ahcresponse.getResponsebody(standardCharsets.utf_8)); } }
您還可以定義自己的自定義BodyWritable
:
公共類myclient {private bobswritable <string> somothermethod(string string){org.apache.pekko.util.bytestring bytestring = org.apache.pekko.util.util.bytestring.fromstring(string)string(string); 返回新的DefaultBodyWritables.inmemorybody撰寫(bytestring,“ text/plain”); } }
獨立客戶端需要Pekko在內部處理流數據:
在Scala中,召集到Web服務並關閉客戶端的方式:
package playwsclientimport org.apache.pekko.actor.ActorSystemimport org.apache.pekko.stream._import play.api.libs.ws._import play.api.libs.ws.ahc._import scala.concurrent.Futureobject ScalaClient { import DefaultBodyReadables. _ 導入scala.concurrent.executioncontext.implicits._ def main(args:array [string]):unit = {//創建用於線程和流媒體管理圖像val val system = actorsystem()的pekko系統() system.registerontermination {system.exit(0) }隱式val材料器= systemMaterializer(系統).materializer //創建獨立ws客戶端//沒有參數默認為由//創建的AHCWSCLIENT CONFIG,從//“ () 致電(WSCLIENT) 。 。 } def呼叫(wsclient:standalOnewsclient):未來[unit] = { wsclient.url(“ http://www.google.com”).get()。map {wendesp => val statustext:string = response.statustext val bodn println(s“得到響應$ statustext:$ body”) } } }
您還可以直接從asynchttpclient實例創建獨立客戶端:
對象scalaclient {def main(args:array [string]):unit = {//使用import play.shaded.ahc.org.asynchtpclient._val asynchttpclientconfig = new defaultAseNAsyAsyAsyAsyAsyNchtttpClientConfig.builder.builder.builder) .setmaxrequestretry(0) .setshutdownquietperiod(0) .setShutDownTimeOut(0).buildval asynchttpClient = new DefaultAsyAsynchttpClient(asynchtttpclientConfig)val wsclient = new startaloneahcwsclient(asynchtttpclient) } }
當有一個asynchttpclient配置選項時,這很有用,該選項在WS配置層中不可用。
在Java中,API大致相同:
package playwsclient; import org.apache.pekko.actor.actorsystem; import org.apache.pekko.stream。 ahc。*;公共類JavaClient實施defaultbody Readables {私有最終的naterAneAhcwsclient客戶端;私人最終ActorSystem System; public static void main (string [] args){//設置pekko材料以操縱流式finefinal system =“ wsclient” =“ wsclient” ActorSystem.Create(name); system.Registerontermination(() - > system.exit(0)); Mitalizer iSerizer材料iSerizer = systemMaterializer.get(system).materializer(); // //從'application.conf`創建ws ws客戶文件,當前的classloader和材料器。 javaclient.run(); } javaclient(ActorSystem System,standaloneahcwsclient client){this.system = System; this.client = client; } public void run(){client.url(“ http://www.google.com”).get() .WHENCOLLETE(((響應,拋出)) - > {String statustext = response.getStatustext(); string body = response.getBody(string(); system.out.ut.println(“獲得響應” + statustext); })) .thenrun(() - > {try {client.close(); } catch(異常E){e.printstacktrace(); } })) .thenrun(系統::終止); } }
同樣,您可以從配置中明確提供AsynchtpClient客戶端:
公共類JavAclient實現DefaultBodyRadables {public static void main(String [] args){// ... //直接從configassynchttpclientconfig asynchttpclient contpclient = New defaultAndAdeaultAsyAsyAsyAsyAsyAsyAsyAsyNchttpClientConfig.builderdig.builderdefig.builderderdefig = asynchttpclient。 .setmaxrequestretry(0) .setshutdownquietperiod(0) .setShutdowntimeout(0) 。 //直接從asynchttpclient.wsclient client = new AHCWSCLIENT(asynchttpclient,Matertializer); // ...}直接設置WSCLIENT實例。 }
播放WS通過Cachingasynchttpclient,Ahchttpcache和Cachecontrol實現HTTP緩存,這是Scala中最小的HTTP高速緩存庫。
要創建使用緩存的獨立AHC客戶端,請在帶有緩存適配器的AHCHTTPCACHE實例中傳遞給基礎實現。 例如,要使用咖啡因作為基礎緩存,您可以使用以下內容:
導入scala.concurrent.futureimport java.util.concurrent.concurrent.timeunitimport com.github.benmanes.caffeine.cache. {caffeine,ticker} import play.api.libs.libs.ws.ws.ws.ws.ws.ws .ahc.stanc.sandaloneahcwsclientimport play.api.api.api.api.api.api.apss.wss.wss.wss.ahcss.ahcss.ahc.wss.ahcs.ahc.ahc.ahc.ahc。 cache。{ahchttpcache ,緩存,有效urike,響應式} class caffeinehttpcache擴展了緩存{val undeslying = caffeine.newbuilder() .ticker(ticker.systemticker()) 。 。 (鍵,輸入))def get(鍵:有效urikey)= future.successful(option(基礎getifpresent鍵))def close():unit = undeslying.cleanup() } def with cache(隱式m:org.apache.pekko.stream.materializer):standaloneahcwsclient = {隱式def ec = m.executionContext val cache = new Caffeinehtttpcache() }
有許多指南有助於將緩存控制標頭組合在一起:
Mozilla的HTTP緩存指南
馬克·諾丁漢的緩存指南
HTTP緩存
休息容易:http緩存
請參閱https://github.com/playframework/.github/blob/main/releasing.md
Play WS是根據Apache許可證(版本2版)許可的。有關更多信息,請參見許可證文件。