Play WS는 Play Team이 Play Framework와 함께 사용하기 위해 원래 개발 한 강력한 HTTP 클라이언트 라이브러리입니다. HTTP 클라이언트 기능에 asynchttpclient를 사용하며 재생 종속성이 없습니다.
우리는 앱에서 Play WS를 사용하는 방법에 대한 문서를 제공했습니다 (플레이없이). Play in Play 사용 방법에 대한 자세한 내용은 Play 문서를 참조하십시오.
시작하려면 SBT의 종속성으로 play-ahc-ws-standalone
추가 할 수 있습니다.
LibraryDependencies += "org.playframework"%% "Play-ahc-WS-Standalone" % "최신_version"// 이전 버전 3.0.0 : LibraryDependencies += "com.typesafe.play"%% "play-ahc-ws- 독립형 " %"최신_version "
이 이미지에 표시된 버전으로 LATEST_VERSION
바꾸는 곳 :.
이것은 Asynchttpclient에 의해 뒷받침되는 독립형 Play WS를 추가합니다. 이 라이브러리에는 Scala와 Java Apis가 모두 play.api.libs.ws
및 play.libs.ws
포함합니다.
Play-Json 또는 Scala XML을 사용하여 XML 및 JSON 지원을 추가하려면 다음을 추가하십시오.
LibraryDependencies += "org.playframework"%% "Play-WS-Standalone-XML" % playwstandaloneversion LibraryDependencies += "org.playframework"%% "Play-WS-Standalone-JSON" % PlaywstandalOneversion // 버전 3.0.0 이전 : librarydependencies += "com.typesafe.play"%% "Play-Ws-Standalone-XML" % playwstandaloneversion LibraryDependencies += "com.typesafe.play"%% "Play-WS-Standalone-JSON" % PlaywStandalOneversion
Play는 play.shaded.ahc
및 play.shaded.oauth
패키지 이름에 각각 다시 포장 된 Asynchttpclient 및 Oauth Signpost의 음영 버전을 사용합니다. Shading Asynchttpclient는 Asynchttpclient 뒤에 사용되는 Netty의 버전이 적용과 완전히 독립적이며 전체적으로 재생된다는 것을 의미합니다.
구체적으로, Shading 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- 테스트를 참조하십시오. 이 버그는 SBT/SBT#2687로 제출되었습니다.
재생 ws 음영 Asynchttpclient, 기본 설정도 음영 처리되므로 AHC 문서를 준수하지 않습니다. 이는 ahc-default.properties
및 usePooledMemory
시스템 속성의 설정이 play.shaded.ahc
와 함께 선정되어 있음을 의미합니다.
play.shaded.ahc.org.asynchttpclient.usepooledmemory = true
Play-WS의 유형 시스템이 변경되어 요청 본문과 응답 본문이 더 풍부한 유형을 사용할 수 있습니다.
자신의 Bodywlitable 또는 BodyRedable을 정의 할 수 있지만 Box 설정의 기본값을 사용하려면 DefaultBodyReadables / DefaultBodyWritables와 함께 유형 매핑을 가져올 수 있습니다.
가져 오기 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을 사용하려면 응답을 명시 적으로 입력해야합니다.
import scala.concurrent. {executionContext, Future} import play.api.libs.ws. standalOnewsclientimport play.api.libs.ws.xmlbodyreadables._ // 필수 핸드 플렉스 (WS : 독립형 EC : ExecutionContext) : 미래 [Scala) : .xml.elem] = ws.url ( "..."). get (). map {respons => response.body [scala.xml.elem] }
또는 Play-Json 사용 :
import scala.concurrent. {executionContext, Future} import play.api.libs.json.json.jsvalueimport play.api.libs.ws. standalOnewsclientimport play.api.libs.ws.jsonbodyreadables._ // resightDef handsJsonResp (ws : standalOnewsclient) 암시 적 EC : executionContext) : 미래 [jsValue] = ws.url ( "..."). get (). map {respons => response.body [jsvalue] }
특별한 경우가 있습니다. 응답을 스트리밍 할 때 신체를 출처로 가져와야합니다.
import scala.concurrent.executioncontextimport org.apache.pekko.util.bytestringimport org.apache.pekko.stream.sourceimport play.api.libs.ws.standalonewsclientDef austStream (ws : stremonewsclient) (emplicit contex). ws.url ( "..."). stream (). map {respons => val 소스 : 소스 [bytestring, _] = response.bodyAssource val _ = source // 소스로 무언가를 수행합니다. }
게시하려면 Bodywlitable의 암시 적 클래스 매핑이있는 유형을 전달해야합니다.
import scala.concurrent.executioncontextimport play.api.libs.ws.defaultbodywritables._ // 필수 사후 검사 (ws : play.api.libs.ws.standalonewsclient) (implicit ec : executionContext) = {val stringdata = "hello world" ws.url ( "..."). post (stringdata) .map {response => / * 뭔가 해 * /} }
자신의 맞춤형 BodyRedable을 정의 할 수도 있습니다.
가져 오기 play.api.libs.ws. bodyreadableimport play.api.libs.ws.ahc.standaloneahcwsresponsecase class foo (body : string) 암시 적 Val fuoBodyReadable = bodyRedable [foo] {response => import play.shaded.ahc.org.asynchttpclient. }
또는 맞춤형 몸통 :
import org.apache.pekko.util.bytestringimport play.api.libs.ws. {bodywlitable, inmemorybody} implicit val writebleof_foo : bodyworditable [foo] = {// https://tools.ietf.org/rfc6838#section -3.2 Bodywlitable (foo => inmemorybody (bytestring.fromstring (foo.tostring)), "application/vnd.company.category+foo") }
Java에서 기본 유형 매핑을 사용하려면 다음을 사용해야합니다.
import play.libs.ws.defaultBodyReadables; import play.libs.ws.defaultBodyWritables;
다음과 같은
public class myclient는 defaultBodyWritables, defaultBodyReadables {public wompletionstage <string> dostuff () {return client.url ( "http://example.com") .post (body ( "hello world"). athapply (응답 -> 응답 .body (String ()) ); } }
특별한 경우가 있습니다. 스트림을 사용할 때는 신체를 출처로 가져와야합니다.
class myclass {public wompletionstage <source <bytestring, notused >> readResponseAsStream () {return ws.url (url) .stream (). whenApply (응답 -> response.bodyAssource () ); } }
소스를 게시 할 수도 있습니다.
class myclass {public wompletionstage <string> dostuff () {source <bytestring, notused> source = fromSource (); return ws.url (url) .post (body (source)). thenApply (응답 -> response.body () ); } }
사용자 정의 BodyReadable
정의 할 수 있습니다.
가져 오기 play.libs.ws.ahc.*; import play.shaded.ahc.org.asynchttpclient.response; 클래스 fooreadable empless bodyreadable <standalonewsresponse, foo> {public foo apply (standalonewsresponse 응답) {응답 ahcresponse = (응답) 응답. getUnderlying (); return foo.serialize (ahcresponse.getResponseBody (StandardCharsets.utf_8)); } }
자신의 맞춤형 BodyWritable
정의 할 수도 있습니다.
공개 클래스 myclient {private bodywlitable <string> someothermethod (string) {org.apache.pekko.util.bytestring bytestring = org.apache.pekko.util.bytestring.fromstring (string); 새로운 DefaultBodyWritables.inMemoryBodyWritable (Bytestring, "Text/Plain")을 반환합니다. } }
독립형 클라이언트는 스트리밍 데이터를 내부적으로 처리하려면 PEKKO가 필요합니다.
Scala에서는 웹 서비스를 호출하고 클라이언트를 닫는 방법입니다.
package playwsclientimport org.apache.pekko.actor.actorsystemport org.apache.pekko.stream._import play.api.libs.ws._import play.api.libs.ws. _ Scala.concurrent.executionContext.implicits._ 가져 오기 def main (args : array [string]) : init = {// 스레드 및 스트리밍에 대한 pekko 시스템 생성 관리 val 시스템 = actorsystem () System.registeronTermination {System.Exit (0) } complicit val materializer = SystemMaterializer (System) .Materializer // 독립형 WS 클라이언트 생성 // "AHCWSCLIENTCONFIGACTORY.FORCONFIG (configatory.load, this.getClass.getClass.GetClassLoader)에서 생성 된 AHCWSCLIENTCONFIG에 대한 인수 없음 기본 사항이 없습니다. () 전화 (wsclient) . andthen {case _ => wsclient.close ()} . andthen {case _ => system.terminate ()} } def call (wsclient : standalonewsclient) : Future [unit] = { wsclient.url ( "http://www.google.com") .get (). map {respons => val statustext : string = response.statustext vol body = response.body [string] println (s "답변이 $ statustext : $ body") } } }
Asynchttpclient 인스턴스에서 직접 독립형 클라이언트를 생성 할 수도 있습니다.
Object Scalaclient {def main (args : array [string]) : init = {// import play.shaded.ahc.org.asynchttpclient._val asynchttpclientconfig = new defaultasynchttpclientConfig.Builder () .SetMaxRequestRetry (0) .SetShutdownQuietPeriod (0) .SetShutdownTimeout (0) .BuildVal Asynchttpclient = 새로운 DefaultAsynchttpclient (asynchttpclientConfig) val wsclient = new SpectalOneahcwSclient (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 Pemptions DefaultBodyReadables {private final final standaloneahcwsclient client; private final actorsystem system; public static void main (string [] args) {// pekko materializer를 설정하여 streamingfinal String name = "wsclient"; Actorsystem System = actorsystem.create (name); System.registerOntermination (() -> system.exit (0)); materializer = systemmaterializer.get (System) .materializer (); //`application.conf`에서 ws 클라이언트를 만듭니다. 파일, 현재 클래스 로더 및 재료화. javaclient.run (); } javaclient (ActorSystem System, standalOneaHcwSclient 클라이언트) {this.system = system; this.client = client; } public void run () {client.url ( "http://www.google.com") .get () .Whencelfete ((응답, 던질 가능) -> {String StatUStext = response.getStatUtext (); String Body = response.getBody (String ()); System.out.println ( "응답 got" + statustext); }) .thenrun (() -> {try {client.close (); } catch (예외 e) {e.printstacktrace (); } }) .thenrun (System :: 종료); } }
마찬가지로 구성에서 Asynchttpclient 클라이언트를 명시 적으로 제공 할 수 있습니다.
공개 클래스 javaclient는 DefaultBodyReadables {public static void main (string [] args) {// ... // configasynchttpclientConfig asynchttpclientConfig에서 직접 asynchttpclient를 설정합니다. .SetMaxRequestRetry (0) .SetShutdownQuietPeriod (0) .SetShutdownTimeout (0) .build (); Asynchttpclient Asynchttpclient = 새로운 DefaultAsynchttpclient (asynchttpclientConfig); // asynchttpclient.wsclient 클라이언트에서 직접 wsclient 인스턴스를 설정합니다. }
재생 WS는 스칼라의 최소 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.libs.ws.ahc. 캐시. {ahchttpcache, 캐시, EffectionErikey, responseentry} class caffeinehtttpcache cache {val indranlying = caffeine.newbuilder () .Ticker (Ticker.SystemTicker ()) .expiratewterwrite (365, TimeUnit.days) . (키, 항목)) def get (key : effectierikey) = future.successful (옵션 (기본 getifpresent key)) def close () : init = indranlying.cleanup () } def withcache (implicit m : org.apache.pekko.stream.materializer) : standaloneahcwsclient = {implicit def ec = m.executionContext val cache = new caffeinehttpcache () StandalOneahcwSclient (httpcache = 일부). }
캐시 제어 헤더를 구성하는 데 도움이되는 가이드가 많이 있습니다.
HTTP 캐싱에 대한 모질라의 안내서
마크 노팅엄의 캐싱 가이드
HTTP 캐싱
쉬운 휴식 : HTTP 캐시
https://github.com/playframework/.github/blob/main/releasing.md를 참조하십시오
Play WS는 Apache 라이센스, 버전 2에 따라 라이센스가 부여됩니다. 자세한 내용은 라이센스 파일을 참조하십시오.