0
# Network Monitoring and Interception
1
2
The v133Network class provides comprehensive network monitoring and interception capabilities, enabling developers to monitor network activity, intercept requests and responses, handle authentication challenges, and modify network behavior.
3
4
## Capabilities
5
6
### v133Network Class
7
8
Main network control class that extends the base Network functionality with v133-specific implementations.
9
10
```java { .api }
11
/**
12
* v133-specific network monitoring and interception implementation
13
* Extends Network<AuthRequired, RequestPaused> for type-safe network operations
14
*/
15
public class v133Network extends Network<AuthRequired, RequestPaused> {
16
private static final Logger LOG = Logger.getLogger(v133Network.class.getName());
17
18
/**
19
* Creates a new v133Network instance
20
* @param devTools DevTools instance for communication with browser
21
*/
22
public v133Network(DevTools devTools);
23
}
24
```
25
26
### User Agent Management
27
28
Control and override the browser's user agent string and related headers.
29
30
```java { .api }
31
/**
32
* Set user agent override for network requests
33
* @param userAgent UserAgent configuration with user agent string, accept language, and platform
34
* @return Command to set user agent override
35
*/
36
protected Command<Void> setUserAgentOverride(UserAgent userAgent);
37
```
38
39
**Usage Example:**
40
41
```java
42
import org.openqa.selenium.devtools.idealized.Network.UserAgent;
43
44
v133Network network = new v133Network(devTools);
45
46
// Set custom user agent
47
UserAgent customUA = new UserAgent(
48
"Custom-Browser/1.0 (Compatible)",
49
"en-US,en;q=0.9",
50
"Custom Platform"
51
);
52
53
devTools.send(network.setUserAgentOverride(customUA));
54
```
55
56
### Network Caching Control
57
58
Enable or disable network caching to control browser cache behavior during testing.
59
60
```java { .api }
61
/**
62
* Enable network caching in the browser
63
* @return Command to enable network caching
64
*/
65
protected Command<Void> enableNetworkCaching();
66
67
/**
68
* Disable network caching in the browser
69
* @return Command to disable network caching
70
*/
71
protected Command<Void> disableNetworkCaching();
72
```
73
74
### Request Interception
75
76
Enable and disable network request interception for comprehensive request/response monitoring and modification.
77
78
```java { .api }
79
/**
80
* Enable fetch interception for all request patterns
81
* Enables interception of both REQUEST and RESPONSE stages
82
* @return Command to enable fetch interception
83
*/
84
protected Command<Void> enableFetchForAllPatterns();
85
86
/**
87
* Disable fetch interception to stop monitoring network requests
88
* @return Command to disable fetch interception
89
*/
90
protected Command<Void> disableFetch();
91
92
/**
93
* Get the request paused event for intercepted requests
94
* @return Event for monitoring paused requests
95
*/
96
public Event<RequestPaused> requestPausedEvent();
97
```
98
99
**Usage Example:**
100
101
```java
102
import org.openqa.selenium.devtools.v133.fetch.model.RequestPaused;
103
104
// Enable request interception
105
devTools.send(network.enableFetchForAllPatterns());
106
107
// Listen for intercepted requests
108
devTools.addListener(network.requestPausedEvent(), (RequestPaused pausedReq) -> {
109
String requestId = network.getRequestId(pausedReq);
110
System.out.println("Intercepted request: " + requestId);
111
112
// Continue without modification
113
devTools.send(network.continueWithoutModification(pausedReq));
114
});
115
```
116
117
### Authentication Handling
118
119
Handle HTTP authentication challenges with credential management.
120
121
```java { .api }
122
/**
123
* Get the authentication required event for HTTP auth challenges
124
* @return Event for monitoring authentication challenges
125
*/
126
protected Event<AuthRequired> authRequiredEvent();
127
128
/**
129
* Get URI from authentication required event
130
* @param authRequired Authentication challenge event
131
* @return URI string that requires authentication
132
*/
133
protected String getUriFrom(AuthRequired authRequired);
134
135
/**
136
* Continue authentication with provided credentials
137
* @param authRequired Authentication challenge event
138
* @param credentials Username and password for authentication
139
* @return Command to provide authentication credentials
140
*/
141
protected Command<Void> continueWithAuth(AuthRequired authRequired, UsernameAndPassword credentials);
142
143
/**
144
* Cancel authentication challenge
145
* @param authRequired Authentication challenge event
146
* @return Command to cancel authentication
147
*/
148
protected Command<Void> cancelAuth(AuthRequired authRequired);
149
```
150
151
**Usage Example:**
152
153
```java
154
import org.openqa.selenium.UsernameAndPassword;
155
import org.openqa.selenium.devtools.v133.fetch.model.AuthRequired;
156
157
// Listen for authentication challenges
158
devTools.addListener(network.authRequiredEvent(), (AuthRequired authReq) -> {
159
String uri = network.getUriFrom(authReq);
160
System.out.println("Authentication required for: " + uri);
161
162
// Provide credentials
163
UsernameAndPassword credentials = new UsernameAndPassword("user", "pass");
164
devTools.send(network.continueWithAuth(authReq, credentials));
165
166
// Or cancel authentication
167
// devTools.send(network.cancelAuth(authReq));
168
});
169
```
170
171
### Request and Response Processing
172
173
Create and process HTTP messages from intercepted network traffic.
174
175
```java { .api }
176
/**
177
* Create Selenium HTTP messages from paused request
178
* @param pausedReq Intercepted request/response
179
* @return Either HttpRequest (for requests) or HttpResponse (for responses)
180
*/
181
public Either<HttpRequest, HttpResponse> createSeMessages(RequestPaused pausedReq);
182
183
/**
184
* Check if paused request has an error response
185
* @param pausedReq Intercepted request
186
* @return true if the request has an error response
187
*/
188
protected boolean hasErrorResponse(RequestPaused pausedReq);
189
190
/**
191
* Get unique request identifier from paused request
192
* @param pausedReq Intercepted request
193
* @return String request ID
194
*/
195
protected String getRequestId(RequestPaused pausedReq);
196
```
197
198
### Request Modification
199
200
Modify intercepted requests and provide custom responses.
201
202
```java { .api }
203
/**
204
* Continue intercepted request without any modifications
205
* @param pausedRequest Intercepted request
206
* @return Command to continue request unchanged
207
*/
208
protected Command<Void> continueWithoutModification(RequestPaused pausedRequest);
209
210
/**
211
* Continue intercepted request with modifications
212
* @param pausedReq Intercepted request
213
* @param req Modified HttpRequest to send instead
214
* @return Command to continue with modified request
215
*/
216
protected Command<Void> continueRequest(RequestPaused pausedReq, HttpRequest req);
217
218
/**
219
* Fulfill intercepted request with custom response
220
* @param pausedReq Intercepted request
221
* @param res Custom HttpResponse to return
222
* @return Command to fulfill request with custom response
223
*/
224
protected Command<Void> fulfillRequest(RequestPaused pausedReq, HttpResponse res);
225
```
226
227
**Usage Example:**
228
229
```java
230
import org.openqa.selenium.remote.http.HttpRequest;
231
import org.openqa.selenium.remote.http.HttpResponse;
232
import org.openqa.selenium.internal.Either;
233
234
// Process intercepted requests
235
devTools.addListener(network.requestPausedEvent(), (RequestPaused pausedReq) -> {
236
Either<HttpRequest, HttpResponse> message = network.createSeMessages(pausedReq);
237
238
if (message.isLeft()) {
239
// Handle request
240
HttpRequest request = message.left();
241
System.out.println("Request: " + request.getMethod() + " " + request.getUri());
242
243
// Modify request if needed
244
if (request.getUri().contains("/api/")) {
245
request.addHeader("X-Test-Header", "Modified by Selenium");
246
devTools.send(network.continueRequest(pausedReq, request));
247
} else {
248
devTools.send(network.continueWithoutModification(pausedReq));
249
}
250
} else {
251
// Handle response
252
HttpResponse response = message.right();
253
System.out.println("Response: " + response.getStatus());
254
255
// Continue with original response
256
devTools.send(network.continueWithoutModification(pausedReq));
257
}
258
});
259
```
260
261
## Network Data Types
262
263
### RequestPaused
264
265
Represents an intercepted network request or response.
266
267
```java { .api }
268
// From org.openqa.selenium.devtools.v133.fetch.model.RequestPaused
269
public class RequestPaused {
270
public RequestId getRequestId(); // Unique request identifier
271
public Request getRequest(); // Request details
272
public Optional<Integer> getResponseStatusCode(); // Response status code (if response)
273
public Optional<List<HeaderEntry>> getResponseHeaders(); // Response headers (if response)
274
public Optional<ErrorReason> getResponseErrorReason(); // Error reason (if failed)
275
}
276
```
277
278
### AuthRequired
279
280
Represents an HTTP authentication challenge.
281
282
```java { .api }
283
// From org.openqa.selenium.devtools.v133.fetch.model.AuthRequired
284
public class AuthRequired {
285
public RequestId getRequestId(); // Request requiring authentication
286
public AuthChallenge getAuthChallenge(); // Authentication challenge details
287
}
288
289
public class AuthChallenge {
290
public String getOrigin(); // Origin requiring authentication
291
public String getScheme(); // Authentication scheme (Basic, Digest, etc.)
292
public Optional<String> getRealm(); // Authentication realm
293
}
294
```
295
296
### Request and Header Types
297
298
```java { .api }
299
// From org.openqa.selenium.devtools.v133.network.model.Request
300
public class Request {
301
public String getUrl(); // Request URL
302
public String getMethod(); // HTTP method
303
public Map<String, String> getHeaders(); // Request headers
304
public Optional<String> getPostData(); // POST data (if applicable)
305
}
306
307
// From org.openqa.selenium.devtools.v133.fetch.model.HeaderEntry
308
public class HeaderEntry {
309
public HeaderEntry(String name, String value);
310
public String getName(); // Header name
311
public String getValue(); // Header value
312
}
313
```
314
315
## Advanced Network Patterns
316
317
### Request Filtering
318
319
Filter and selectively process network requests based on criteria:
320
321
```java
322
devTools.addListener(network.requestPausedEvent(), (RequestPaused pausedReq) -> {
323
Either<HttpRequest, HttpResponse> message = network.createSeMessages(pausedReq);
324
325
if (message.isLeft()) {
326
HttpRequest request = message.left();
327
String url = request.getUri().toString();
328
329
// Filter by URL pattern
330
if (url.contains("/api/sensitive")) {
331
// Block sensitive requests
332
HttpResponse blockedResponse = new HttpResponse()
333
.setStatus(403)
334
.setContent(() -> new ByteArrayInputStream("Blocked".getBytes()));
335
devTools.send(network.fulfillRequest(pausedReq, blockedResponse));
336
} else if (url.contains("/api/")) {
337
// Modify API requests
338
request.addHeader("Authorization", "Bearer test-token");
339
devTools.send(network.continueRequest(pausedReq, request));
340
} else {
341
// Continue other requests unchanged
342
devTools.send(network.continueWithoutModification(pausedReq));
343
}
344
} else {
345
devTools.send(network.continueWithoutModification(pausedReq));
346
}
347
});
348
```
349
350
### Response Mocking
351
352
Create mock responses for testing:
353
354
```java
355
import java.io.ByteArrayInputStream;
356
357
devTools.addListener(network.requestPausedEvent(), (RequestPaused pausedReq) -> {
358
Either<HttpRequest, HttpResponse> message = network.createSeMessages(pausedReq);
359
360
if (message.isLeft()) {
361
HttpRequest request = message.left();
362
363
if (request.getUri().toString().contains("/api/mock")) {
364
// Create mock response
365
String mockData = "{\"status\":\"mocked\",\"data\":[1,2,3]}";
366
HttpResponse mockResponse = new HttpResponse()
367
.setStatus(200)
368
.addHeader("Content-Type", "application/json")
369
.setContent(() -> new ByteArrayInputStream(mockData.getBytes()));
370
371
devTools.send(network.fulfillRequest(pausedReq, mockResponse));
372
} else {
373
devTools.send(network.continueWithoutModification(pausedReq));
374
}
375
} else {
376
devTools.send(network.continueWithoutModification(pausedReq));
377
}
378
});
379
```
380
381
## Error Handling
382
383
Network operations include comprehensive error handling for:
384
385
- **Request Timeout**: When network requests exceed timeout limits
386
- **Authentication Failures**: When credentials are invalid or rejected
387
- **Connection Errors**: When network connections fail or are interrupted
388
- **Protocol Violations**: When HTTP protocol rules are violated
389
- **Content Processing**: When request/response content cannot be processed