Asynchronous HTTP client for Play Framework with OAuth, OpenID, and SSL/TLS support
npx @tessl/cli install tessl/maven-com-typesafe-play--play-ws-2-10@2.4.00
# Play WS
1
2
Play WS is a powerful asynchronous HTTP client library for the Play Framework. It provides comprehensive WebService client functionality built on top of the Ning AsyncHttpClient, supporting OAuth authentication, OpenID authentication, SSL/TLS configuration, and seamless integration with Play's reactive streaming model.
3
4
## Package Information
5
6
- **Package Name**: play-ws_2.10
7
- **Package Type**: maven
8
- **Language**: Scala/Java
9
- **Installation**:
10
- Scala: Add to build.sbt: `"com.typesafe.play" %% "play-ws" % "2.4.11"`
11
- Java: Add to build.sbt: `"com.typesafe.play" % "play-java-ws_2.10" % "2.4.11"`
12
13
## Core Imports
14
15
### Scala API
16
17
```scala
18
import play.api.libs.ws._
19
import play.api.libs.ws.ning._
20
import play.api.Application
21
import scala.concurrent.Future
22
```
23
24
For dependency injection:
25
26
```scala
27
import javax.inject.Inject
28
import play.api.libs.ws.WSClient
29
30
class MyService @Inject()(ws: WSClient) {
31
// Use ws client
32
}
33
```
34
35
### Java API
36
37
```java
38
import play.libs.ws.*;
39
import play.libs.F.Promise;
40
import java.util.concurrent.CompletionStage;
41
```
42
43
For dependency injection:
44
45
```java
46
import javax.inject.Inject;
47
import play.libs.ws.WSClient;
48
49
public class MyService {
50
private final WSClient ws;
51
52
@Inject
53
public MyService(WSClient ws) {
54
this.ws = ws;
55
}
56
}
57
```
58
59
## Basic Usage
60
61
### Scala API
62
63
```scala
64
import play.api.libs.ws._
65
import play.api.Application
66
import scala.concurrent.Future
67
import scala.concurrent.ExecutionContext.Implicits.global
68
69
implicit val app: Application = // Your Play application
70
71
// Simple GET request
72
val futureResponse: Future[WSResponse] = WS.url("https://api.example.com/users").get()
73
74
// POST with JSON body
75
val jsonData = Json.obj("name" -> "John", "email" -> "john@example.com")
76
val postResponse: Future[WSResponse] = WS.url("https://api.example.com/users")
77
.withHeaders("Content-Type" -> "application/json")
78
.post(jsonData)
79
80
// Handle response
81
futureResponse.map { response =>
82
println(s"Status: ${response.status}")
83
println(s"Body: ${response.body}")
84
val jsonBody = response.json
85
}
86
```
87
88
### Java API
89
90
```java
91
import play.libs.ws.*;
92
import play.libs.F.Promise;
93
import com.fasterxml.jackson.databind.JsonNode;
94
import com.fasterxml.jackson.databind.node.ObjectNode;
95
import play.libs.Json;
96
97
// Simple GET request
98
Promise<WSResponse> responsePromise = WS.url("https://api.example.com/users").get();
99
100
// POST with JSON body
101
ObjectNode jsonData = Json.newObject();
102
jsonData.put("name", "John");
103
jsonData.put("email", "john@example.com");
104
105
Promise<WSResponse> postPromise = WS.url("https://api.example.com/users")
106
.setHeader("Content-Type", "application/json")
107
.post(jsonData);
108
109
// Handle response
110
responsePromise.map(response -> {
111
System.out.println("Status: " + response.getStatus());
112
System.out.println("Body: " + response.getBody());
113
JsonNode jsonBody = response.asJson();
114
return response;
115
});
116
```
117
118
## Architecture
119
120
Play WS is built around several key components:
121
122
- **Core HTTP Client**: `WS`, `WSClient`, `WSRequest`, and `WSResponse` providing the main HTTP client API
123
- **Ning Implementation**: `NingWSClient` providing the actual HTTP implementation using Ning AsyncHttpClient
124
- **Authentication**: OAuth 1.0a and OpenID support for secure API access
125
- **SSL/TLS Configuration**: Comprehensive SSL configuration system for secure connections
126
- **Reactive Streaming**: Integration with Play's iteratees for streaming large responses
127
- **Dependency Injection**: Full support for Play's dependency injection system
128
129
## Capabilities
130
131
### HTTP Client Operations
132
133
Core HTTP client functionality for making RESTful API calls, handling responses, and managing connection settings.
134
135
#### Scala API
136
137
```scala { .api }
138
object WS {
139
def client(implicit app: Application): WSClient
140
def url(url: String)(implicit app: Application): WSRequest
141
def clientUrl(url: String)(implicit client: WSClient): WSRequest
142
}
143
144
trait WSClient {
145
def underlying[T]: T
146
def url(url: String): WSRequest
147
def close(): Unit
148
}
149
150
trait WSRequest {
151
def get(): Future[WSResponse]
152
def post[T](body: T)(implicit wrt: Writeable[T]): Future[WSResponse]
153
def put[T](body: T)(implicit wrt: Writeable[T]): Future[WSResponse]
154
def patch[T](body: T)(implicit wrt: Writeable[T]): Future[WSResponse]
155
def delete(): Future[WSResponse]
156
def head(): Future[WSResponse]
157
def options(): Future[WSResponse]
158
}
159
```
160
161
#### Java API
162
163
```java { .api }
164
public class WS {
165
public static WSClient client()
166
public static WSRequest url(String url)
167
public static WSClient newClient(int port)
168
}
169
170
public interface WSClient extends Closeable {
171
WSRequest url(String url)
172
Object getUnderlying()
173
void close()
174
}
175
176
public interface WSRequest {
177
Promise<WSResponse> get()
178
Promise<WSResponse> post(Object body)
179
Promise<WSResponse> put(Object body)
180
Promise<WSResponse> patch(Object body)
181
Promise<WSResponse> delete()
182
Promise<WSResponse> head()
183
Promise<WSResponse> options()
184
Promise<WSResponse> execute()
185
WSRequest setHeader(String name, String value)
186
WSRequest setQueryParameter(String name, String value)
187
WSRequest setAuth(String username, String password, WSAuthScheme scheme)
188
WSRequest setBody(Object body)
189
WSRequest setMethod(String method)
190
}
191
```
192
193
[HTTP Client](./http-client.md)
194
195
### OAuth Authentication
196
197
OAuth 1.0a authentication support for secure API access with consumer keys and request tokens.
198
199
```scala { .api }
200
case class OAuth(info: ServiceInfo, use10a: Boolean = true) {
201
def retrieveRequestToken(callbackURL: String): Either[OAuthException, RequestToken]
202
def retrieveAccessToken(token: RequestToken, verifier: String): Either[OAuthException, RequestToken]
203
def redirectUrl(token: String): String
204
}
205
206
case class OAuthCalculator(consumerKey: ConsumerKey, requestToken: RequestToken) extends WSSignatureCalculator
207
```
208
209
[OAuth Authentication](./oauth.md)
210
211
### OpenID Authentication
212
213
OpenID authentication support for identity verification and user attribute exchange.
214
215
```scala { .api }
216
object OpenID {
217
def redirectURL(
218
openID: String,
219
callbackURL: String,
220
axRequired: Seq[(String, String)] = Seq.empty,
221
axOptional: Seq[(String, String)] = Seq.empty,
222
realm: Option[String] = None
223
)(implicit app: Application): Future[String]
224
225
def verifiedId(implicit request: Request[_], app: Application): Future[UserInfo]
226
}
227
```
228
229
[OpenID Authentication](./openid.md)
230
231
### SSL/TLS Configuration
232
233
Comprehensive SSL and TLS configuration system for secure HTTPS connections with custom certificates, protocols, and security settings.
234
235
```scala { .api }
236
case class SSLConfig(
237
default: Boolean = false,
238
protocol: String = "TLSv1.2",
239
enabledProtocols: Option[Seq[String]] = Some(Seq("TLSv1.2", "TLSv1.1", "TLSv1")),
240
enabledCipherSuites: Option[Seq[String]] = None,
241
keyManagerConfig: KeyManagerConfig = KeyManagerConfig(),
242
trustManagerConfig: TrustManagerConfig = TrustManagerConfig(),
243
debug: SSLDebugConfig = SSLDebugConfig(),
244
loose: SSLLooseConfig = SSLLooseConfig()
245
)
246
```
247
248
[SSL Configuration](./ssl.md)
249
250
### Ning HTTP Client Implementation
251
252
Ning AsyncHttpClient-based implementation providing the actual HTTP transport layer with advanced configuration options.
253
254
```scala { .api }
255
case class NingWSClient(config: AsyncHttpClientConfig) extends WSClient {
256
def url(url: String): WSRequest
257
def close(): Unit
258
}
259
260
case class NingWSClientConfig(
261
wsClientConfig: WSClientConfig = WSClientConfig(),
262
allowPoolingConnection: Boolean = true,
263
maxConnectionsPerHost: Int = -1,
264
maxConnectionsTotal: Int = -1
265
)
266
```
267
268
[Ning Implementation](./ning.md)
269
270
### Test Support
271
272
Testing utilities for HTTP client operations in Play applications.
273
274
```scala { .api }
275
trait WsTestClient {
276
def wsCall(call: Call)(implicit port: Port, client: WSClient): WSRequest
277
def wsUrl(url: String)(implicit port: Port, client: WSClient): WSRequest
278
def withClient[T](block: WSClient => T)(implicit port: play.api.http.Port): T
279
}
280
```
281
282
[Test Support](./testing.md)
283
284
## Types
285
286
### Scala API Types
287
288
```scala { .api }
289
trait WSResponse {
290
def status: Int
291
def statusText: String
292
def header(key: String): Option[String]
293
def allHeaders: Map[String, Seq[String]]
294
def cookies: Seq[WSCookie]
295
def cookie(name: String): Option[WSCookie]
296
def body: String
297
def xml: Elem
298
def json: JsValue
299
def bodyAsBytes: Array[Byte]
300
}
301
302
trait WSCookie {
303
def name: String
304
def value: String
305
def domain: String
306
def path: Option[String]
307
def maxAge: Option[Long]
308
def secure: Boolean
309
def httpOnly: Boolean
310
}
311
312
sealed trait WSBody
313
case class InMemoryBody(bytes: Array[Byte]) extends WSBody
314
case class FileBody(file: File) extends WSBody
315
case class StreamedBody(bytes: Enumerator[Array[Byte]]) extends WSBody
316
case object EmptyBody extends WSBody
317
318
case class WSClientConfig(
319
connectionTimeout: Duration = 2.minutes,
320
idleTimeout: Duration = 2.minutes,
321
requestTimeout: Duration = 2.minutes,
322
followRedirects: Boolean = true,
323
useProxyProperties: Boolean = true,
324
userAgent: Option[String] = None,
325
compressionEnabled: Boolean = false,
326
ssl: SSLConfig = SSLConfig()
327
)
328
329
trait WSProxyServer {
330
def host: String
331
def port: Int
332
def protocol: Option[String]
333
def principal: Option[String]
334
def password: Option[String]
335
}
336
337
sealed trait WSAuthScheme
338
object WSAuthScheme {
339
case object BASIC extends WSAuthScheme
340
case object DIGEST extends WSAuthScheme
341
case object NTLM extends WSAuthScheme
342
case object SPNEGO extends WSAuthScheme
343
case object KERBEROS extends WSAuthScheme
344
case object NONE extends WSAuthScheme
345
}
346
```
347
348
### Java API Types
349
350
```java { .api }
351
public interface WSResponse {
352
int getStatus()
353
String getStatusText()
354
String getHeader(String key)
355
Map<String, List<String>> getAllHeaders()
356
List<WSCookie> getCookies()
357
WSCookie getCookie(String name)
358
String getBody()
359
Document asXml()
360
JsonNode asJson()
361
InputStream getBodyAsStream()
362
byte[] asByteArray()
363
}
364
365
public interface WSCookie {
366
String getName()
367
String getValue()
368
String getDomain()
369
String getPath()
370
Long getMaxAge()
371
Boolean isSecure()
372
Boolean isHttpOnly()
373
}
374
375
public enum WSAuthScheme {
376
BASIC, DIGEST, NTLM, SPNEGO, KERBEROS, NONE
377
}
378
```