or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

capabilities-management.mdcommand-execution.mddistributed-tracing.mddriver-services.mdhttp-communication.mdindex.mdwebdriver-operations.md

http-communication.mddocs/

0

# HTTP Communication

1

2

Comprehensive HTTP client infrastructure with support for WebSocket connections, request/response handling, routing, and connection management. This system provides the transport layer for all WebDriver communications and includes advanced features like filtering, routing, and real-time messaging.

3

4

## Capabilities

5

6

### HttpClient Interface

7

8

Core HTTP client interface providing both synchronous and asynchronous request capabilities, along with WebSocket support.

9

10

```java { .api }

11

/**

12

* HTTP client interface for WebDriver communications

13

*/

14

public interface HttpClient extends Closeable {

15

16

/**

17

* Execute HTTP request synchronously

18

* @param req The HTTP request to execute

19

* @return HTTP response

20

*/

21

HttpResponse execute(HttpRequest req);

22

23

/**

24

* Execute HTTP request asynchronously

25

* @param req The HTTP request to execute

26

* @return CompletableFuture containing the HTTP response

27

*/

28

CompletableFuture<HttpResponse> executeAsync(HttpRequest req);

29

30

/**

31

* Open WebSocket connection

32

* @param request HTTP request for WebSocket upgrade

33

* @param listener WebSocket event listener

34

* @return WebSocket instance

35

*/

36

WebSocket openSocket(HttpRequest request, WebSocket.Listener listener);

37

38

void close();

39

40

/**

41

* Factory interface for creating HTTP clients

42

*/

43

interface Factory {

44

HttpClient createClient(ClientConfig config);

45

}

46

47

// Static factory methods

48

static Factory create(String name);

49

static Factory createDefault();

50

}

51

```

52

53

**Usage Examples:**

54

55

```java

56

import org.openqa.selenium.remote.http.HttpClient;

57

import org.openqa.selenium.remote.http.HttpRequest;

58

import org.openqa.selenium.remote.http.HttpResponse;

59

import org.openqa.selenium.remote.http.ClientConfig;

60

61

// Create HTTP client

62

HttpClient.Factory factory = HttpClient.createDefault();

63

ClientConfig config = ClientConfig.defaultConfig()

64

.baseUrl(new URL("http://localhost:4444"));

65

HttpClient client = factory.createClient(config);

66

67

// Synchronous request

68

HttpRequest request = new HttpRequest(HttpMethod.GET, "/status");

69

HttpResponse response = client.execute(request);

70

71

// Asynchronous request

72

CompletableFuture<HttpResponse> futureResponse = client.executeAsync(request);

73

HttpResponse asyncResponse = futureResponse.get();

74

75

// Cleanup

76

client.close();

77

```

78

79

### ClientConfig

80

81

HTTP client configuration for connection settings, timeouts, filters, and base URLs.

82

83

```java { .api }

84

/**

85

* Configuration for HTTP clients

86

*/

87

public class ClientConfig {

88

89

// Factory method

90

public static ClientConfig defaultConfig();

91

92

// Configuration methods

93

public ClientConfig baseUrl(URL baseUrl);

94

public ClientConfig baseUrl(URI baseUri);

95

public ClientConfig withFilter(Filter filter);

96

public ClientConfig readTimeout(Duration timeout);

97

public ClientConfig connectionTimeout(Duration timeout);

98

99

// Accessor methods

100

public URL baseUrl();

101

public URI baseUri();

102

public Duration readTimeout();

103

public Duration connectionTimeout();

104

public Filter filter();

105

}

106

```

107

108

**Usage Examples:**

109

110

```java

111

import org.openqa.selenium.remote.http.ClientConfig;

112

import org.openqa.selenium.remote.http.AddSeleniumUserAgent;

113

import java.time.Duration;

114

115

// Configure HTTP client

116

ClientConfig config = ClientConfig.defaultConfig()

117

.baseUrl(new URL("http://selenium-grid:4444"))

118

.readTimeout(Duration.ofSeconds(30))

119

.connectionTimeout(Duration.ofSeconds(10))

120

.withFilter(new AddSeleniumUserAgent());

121

```

122

123

### HTTP Request/Response

124

125

Core HTTP message types for request/response communication.

126

127

```java { .api }

128

/**

129

* Represents an HTTP request

130

*/

131

public class HttpRequest extends HttpMessage<HttpRequest> {

132

133

public HttpRequest(HttpMethod method, String uri);

134

135

public HttpMethod getMethod();

136

public String getUri();

137

public String getQueryParameter(String name);

138

public Iterable<String> getQueryParameterNames();

139

public void setContent(Contents.Supplier content);

140

public Contents.Supplier getContent();

141

}

142

143

/**

144

* Represents an HTTP response

145

*/

146

public class HttpResponse extends HttpMessage<HttpResponse> {

147

148

public int getStatus();

149

public void setStatus(int status);

150

public Iterable<String> getHeaderNames();

151

public Iterable<String> getHeaders(String name);

152

public String getHeader(String name);

153

public void setHeader(String name, String value);

154

public void addHeader(String name, String value);

155

public void removeHeader(String name);

156

public void setContent(Contents.Supplier content);

157

public Contents.Supplier getContent();

158

}

159

160

/**

161

* HTTP methods enumeration

162

*/

163

public enum HttpMethod {

164

DELETE, GET, POST, PUT

165

}

166

```

167

168

**Usage Examples:**

169

170

```java

171

import org.openqa.selenium.remote.http.*;

172

173

// Create HTTP request

174

HttpRequest request = new HttpRequest(HttpMethod.POST, "/session");

175

request.setHeader("Content-Type", "application/json");

176

request.setContent(Contents.utf8String("{\"capabilities\":{}}"));

177

178

// Add query parameters

179

String param = request.getQueryParameter("timeout");

180

181

// Process HTTP response

182

HttpResponse response = client.execute(request);

183

int status = response.getStatus();

184

String contentType = response.getHeader("Content-Type");

185

String body = Contents.string(response);

186

```

187

188

### WebSocket Support

189

190

Real-time bidirectional communication support for advanced WebDriver features.

191

192

```java { .api }

193

/**

194

* WebSocket interface for real-time communication

195

*/

196

public interface WebSocket extends Closeable {

197

198

WebSocket send(Message message);

199

void close();

200

void abort();

201

202

/**

203

* WebSocket event listener interface

204

*/

205

interface Listener {

206

void onOpen(WebSocket webSocket);

207

void onText(CharSequence data);

208

void onBinary(byte[] data);

209

void onClose(int code, String reason);

210

void onError(Throwable cause);

211

}

212

}

213

214

/**

215

* Base interface for WebSocket messages

216

*/

217

public interface Message {

218

}

219

220

/**

221

* Text WebSocket message

222

*/

223

public class TextMessage implements Message {

224

public TextMessage(String text);

225

public String text();

226

}

227

228

/**

229

* Binary WebSocket message

230

*/

231

public class BinaryMessage implements Message {

232

public BinaryMessage(byte[] data);

233

public byte[] data();

234

}

235

236

/**

237

* WebSocket close message

238

*/

239

public class CloseMessage implements Message {

240

public CloseMessage(int code, String reason);

241

public int code();

242

public String reason();

243

}

244

```

245

246

**Usage Examples:**

247

248

```java

249

import org.openqa.selenium.remote.http.*;

250

251

// WebSocket listener implementation

252

WebSocket.Listener listener = new WebSocket.Listener() {

253

@Override

254

public void onOpen(WebSocket webSocket) {

255

System.out.println("WebSocket opened");

256

webSocket.send(new TextMessage("Hello Server"));

257

}

258

259

@Override

260

public void onText(CharSequence data) {

261

System.out.println("Received: " + data);

262

}

263

264

@Override

265

public void onClose(int code, String reason) {

266

System.out.println("WebSocket closed: " + code + " " + reason);

267

}

268

269

@Override

270

public void onError(Throwable cause) {

271

cause.printStackTrace();

272

}

273

274

@Override

275

public void onBinary(byte[] data) {

276

System.out.println("Received binary data of length: " + data.length);

277

}

278

};

279

280

// Open WebSocket connection

281

HttpRequest wsRequest = new HttpRequest(HttpMethod.GET, "/ws");

282

WebSocket webSocket = client.openSocket(wsRequest, listener);

283

284

// Send messages

285

webSocket.send(new TextMessage("Hello"));

286

webSocket.send(new BinaryMessage("binary data".getBytes()));

287

webSocket.send(new CloseMessage(1000, "Normal closure"));

288

```

289

290

### HTTP Filtering

291

292

Request/response filtering system for adding cross-cutting concerns like authentication, logging, and retry logic.

293

294

```java { .api }

295

/**

296

* HTTP request/response filter interface

297

*/

298

public interface Filter {

299

HttpHandler apply(HttpHandler next);

300

}

301

302

/**

303

* Functional interface for handling HTTP requests

304

*/

305

public interface HttpHandler {

306

HttpResponse execute(HttpRequest req) throws UncheckedIOException;

307

}

308

```

309

310

**Usage Examples:**

311

312

```java

313

import org.openqa.selenium.remote.http.*;

314

315

// Custom authentication filter

316

Filter authFilter = next -> req -> {

317

req.setHeader("Authorization", "Bearer " + getToken());

318

return next.execute(req);

319

};

320

321

// Logging filter

322

Filter loggingFilter = next -> req -> {

323

System.out.println("Executing: " + req.getMethod() + " " + req.getUri());

324

HttpResponse response = next.execute(req);

325

System.out.println("Response: " + response.getStatus());

326

return response;

327

};

328

329

// Use filters in client config

330

ClientConfig config = ClientConfig.defaultConfig()

331

.withFilter(authFilter)

332

.withFilter(loggingFilter);

333

```

334

335

### Built-in Filters

336

337

Pre-built filters for common functionality.

338

339

```java { .api }

340

/**

341

* Filter to add Selenium user agent headers

342

*/

343

public class AddSeleniumUserAgent implements Filter {

344

public HttpHandler apply(HttpHandler next);

345

}

346

347

/**

348

* Filter for debugging HTTP exchanges

349

*/

350

public class DumpHttpExchangeFilter implements Filter {

351

public DumpHttpExchangeFilter();

352

public HttpHandler apply(HttpHandler next);

353

}

354

355

/**

356

* Filter for HTTP request retries

357

*/

358

public class RetryRequest implements Filter {

359

public RetryRequest();

360

public HttpHandler apply(HttpHandler next);

361

}

362

```

363

364

### HTTP Routing

365

366

URL routing and template matching system for handling HTTP requests.

367

368

```java { .api }

369

/**

370

* HTTP routing utilities

371

*/

372

public class Route implements HttpHandler, Routable {

373

374

// Static factory methods

375

public static Route matching(Predicate<HttpRequest> predicate);

376

public static Route get(String template);

377

public static Route post(String template);

378

public static Route put(String template);

379

public static Route delete(String template);

380

381

// Configuration methods

382

public Route to(Supplier<HttpHandler> handler);

383

public Route to(HttpHandler handler);

384

385

public HttpResponse execute(HttpRequest req);

386

}

387

388

/**

389

* URL template matching and parsing

390

*/

391

public class UrlTemplate {

392

393

public UrlTemplate(String template);

394

395

public boolean match(String url);

396

public Match match(HttpRequest request);

397

public String expand(Map<String, Object> parameters);

398

399

public static class Match {

400

public Map<String, String> getParameters();

401

public String getUrl();

402

}

403

}

404

405

/**

406

* URL path utilities

407

*/

408

public class UrlPath {

409

410

public static UrlPath relativeUrl(String url);

411

412

public String path();

413

public Map<String, List<String>> parameters();

414

}

415

```

416

417

**Usage Examples:**

418

419

```java

420

import org.openqa.selenium.remote.http.*;

421

import java.util.Map;

422

423

// URL template matching

424

UrlTemplate template = new UrlTemplate("/session/{sessionId}/element");

425

boolean matches = template.match("/session/abc123/element");

426

UrlTemplate.Match match = template.match(request);

427

Map<String, String> params = match.getParameters();

428

String sessionId = params.get("sessionId");

429

430

// HTTP routing

431

Route sessionRoute = Route.post("/session")

432

.to(req -> {

433

// Handle new session creation

434

return new HttpResponse().setStatus(200);

435

});

436

437

Route elementRoute = Route.get("/session/{sessionId}/element/{elementId}")

438

.to(() -> new ElementHandler());

439

440

// Path utilities

441

UrlPath path = UrlPath.relativeUrl("/status?ready=true");

442

String pathString = path.path(); // "/status"

443

Map<String, List<String>> queryParams = path.parameters(); // {"ready": ["true"]}

444

```

445

446

### HTTP Content Utilities

447

448

Utilities for handling HTTP request/response content in various formats.

449

450

```java { .api }

451

/**

452

* HTTP content utilities

453

*/

454

public class Contents {

455

456

// Content factories

457

public static Contents.Supplier utf8String(String text);

458

public static Contents.Supplier bytes(byte[] bytes);

459

public static Contents.Supplier empty();

460

461

// Content extractors

462

public static String string(HttpRequest request);

463

public static String string(HttpResponse response);

464

public static byte[] bytes(Contents.Supplier supplier);

465

466

/**

467

* Content supplier interface

468

*/

469

public interface Supplier {

470

InputStream get();

471

}

472

}

473

```

474

475

**Usage Examples:**

476

477

```java

478

import org.openqa.selenium.remote.http.Contents;

479

480

// Create content

481

Contents.Supplier jsonContent = Contents.utf8String("{\"key\":\"value\"}");

482

Contents.Supplier binaryContent = Contents.bytes(fileData);

483

Contents.Supplier emptyContent = Contents.empty();

484

485

// Set request content

486

HttpRequest request = new HttpRequest(HttpMethod.POST, "/data");

487

request.setContent(jsonContent);

488

489

// Extract response content

490

HttpResponse response = client.execute(request);

491

String responseText = Contents.string(response);

492

byte[] responseBytes = Contents.bytes(response.getContent());

493

```

494

495

### JDK HTTP Implementation

496

497

Built-in HTTP client implementation using Java's native HTTP client.

498

499

```java { .api }

500

/**

501

* JDK-based HTTP client implementation

502

*/

503

public class JdkHttpClient implements HttpClient {

504

505

public HttpResponse execute(HttpRequest req);

506

public CompletableFuture<HttpResponse> executeAsync(HttpRequest req);

507

public WebSocket openSocket(HttpRequest request, WebSocket.Listener listener);

508

public void close();

509

}

510

```