How to use NetworkInterceptor class of org.openqa.selenium.devtools package

Best Selenium code snippet using org.openqa.selenium.devtools.NetworkInterceptor

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1// Licensed to the Software Freedom Conservancy (SFC) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The SFC licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18package org.openqa.selenium.support.devtools;
19
20import org.openqa.selenium.WebDriver;
21import org.openqa.selenium.devtools.DevTools;
22import org.openqa.selenium.devtools.HasDevTools;
23import org.openqa.selenium.devtools.idealized.Network;
24import org.openqa.selenium.devtools.idealized.OpaqueKey;
25import org.openqa.selenium.internal.Require;
26import org.openqa.selenium.remote.http.HttpResponse;
27import org.openqa.selenium.remote.http.Route;
28
29import java.io.Closeable;
30
31import static org.openqa.selenium.remote.http.Contents.utf8String;
32
33/**
34 * Provides a mechanism for stubbing out responses to requests in drivers which
35 * implement {@link HasDevTools}. Usage is done by specifying a {@link Route},
36 * which will be checked for every request to see if that request should be
37 * handled or not. Note that the URLs given to the {@code Route} will be fully
38 * qualified.
39 * <p>
40 * Example usage:
41 * <p>
42 * <code>
43 *   Route route = Route.matching(req -&gt; GET == req.getMethod() &amp;&amp; req.getUri().endsWith("/example"))
44 *     .to(() -&gt; req -&gt; new HttpResponse().setContent(Contents.utf8String("Hello, World!")));
45 *
46 *   try (NetworkInterceptor interceptor = new NetworkInterceptor(driver, route)) {
47 *     // Your code here.
48 *   }
49 * </code>
50 */
51public class NetworkInterceptor implements Closeable {
52
53  public static final HttpResponse PROCEED_WITH_REQUEST = new HttpResponse()
54    .addHeader("Selenium-Interceptor", "Continue")
55    .setContent(utf8String("Original request should proceed"));
56
57  private final OpaqueKey key;
58  private final Network<?, ?> network;
59
60  public NetworkInterceptor(WebDriver driver, Route route) {
61    if (!(driver instanceof HasDevTools)) {
62      throw new IllegalArgumentException("WebDriver instance must implement HasDevTools");
63    }
64    Require.nonNull("Route", route);
65
66    DevTools devTools = ((HasDevTools) driver).getDevTools();
67    devTools.createSessionIfThereIsNotOne();
68
69    network = devTools.getDomains().network();
70
71    key = network.addRequestHandler(route);
72  }
73
74  @Override
75  public void close() {
76    network.removeRequestHandler(key);
77  }
78}
79
Full Screen
copy
1{
2{
3    okHttpClient = new OkHttpClient.Builder()
4        .addNetworkInterceptor(new LoggingInterceptor())
5        .build();
6}
7
8private class LoggingInterceptor implements Interceptor {
9    @Override public Response intercept(Chain chain) throws IOException {
10        Request request = chain.request();
11        Response response = chain.proceed(request);
12
13        utils.log("LoggingInterceptor", "isRedirect=" + response.isRedirect());
14        utils.log("LoggingInterceptor", "responseCode=" + response.code());
15        utils.log("LoggingInterceptor", "redirectUri=" + response.header("Location"));
16
17        return response;
18    }
19}
20
Full Screen
copy
1        OkHttpClient httpClient = new OkHttpClient.Builder()
2            .addNetworkInterceptor(new Interceptor() {
3                @Override
4                public Response intercept(Chain chain) throws IOException {
5                    System.out.println("url: " + chain.request().url());
6                    return chain.proceed(chain.request());
7                }
8            })
9            .build();
10    System.out.println(httpClient.newCall(new Request.Builder().url("http://google.com").build()).execute());
11
Full Screen
copy
1public static void send(JSONObject obj){
2    new OkHttpClient().newCall(new Request.Builder()
3            .addHeader("Content-Type", "application/json")
4            .url("URL...")
5            .post(RequestBody.create(
6                    MediaType.parse("application/json; charset=utf-8"),
7                    obj.toString())
8            ).build())
9    .enqueue(new Callback() {
10        @Override
11        public void onFailure(Call call, IOException e) {
12            Log.d("ZAKA",e.getMessage());
13        }
14        @Override
15        public void onResponse(Call call, Response response) throws IOException {
16            Log.d("ZAKA","Report : -> "+response.body().string());
17        }
18    });
19}
20
Full Screen
copy
1JSObject obj = new JSObject();
2obj.put("token","your token");
3send(obj); // Call send method
4
Full Screen
copy
1Logger logger = LoggerFactory.getLogger(HttpUtil.class);
2HttpLoggingInterceptor logging =
3    new HttpLoggingInterceptor((msg) -> {
4        logger.debug(msg);
5    });
6logging.setLevel(Level.BODY);
7
8client.addNetworkInterceptor(logging);
9
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Most used methods in NetworkInterceptor

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)