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(((响应,throwable) - > {字符串statustext = response.getStatustext(); string body = wenders.get.getBody(string(); system.out.ut.println(“ get a revespon” + 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版)许可的。有关更多信息,请参见许可证文件。