New version is available You are viewing the documentation for JxBrowser 6 which is not supported since December 2019. Go to the current documentation.

This guide shows how to work with the network-related functionality such as proxy, network events, authentication, TLS, client certificate authentication, etc.

Server Whitelist

HTTP Server Authorization Whitelist

You can configure HTTP server authorization whitelist that represents a string with a list of comma/semicolon separated URLs. For example:

Browser browser = new Browser();
BrowserContext browserContext = browser.getContext();
NetworkService networkService = browserContext.getNetworkService();
networkService.setServerWhiteList("*google.com,*example.com,*baz");

HTTP Network Delegate Whitelist

To configure HTTP network delegate whitelist you can use the approach described below:

Browser browser = new Browser();
BrowserContext browserContext = browser.getContext();
NetworkService networkService = browserContext.getNetworkService();
networkService.setDelegateWhiteList("*google.com,*example.com,*baz");

TLS

Handling Certificate Errors

By default JxBrowser allows loading HTTPS web sites with invalid SSL certificates. If you need to change this default behavior and don’t allow invalid SSL certificates, you can register your own LoadHandler implementation where you decide whether invalid SSL certificates should be ignored or not. For example:

browser.setLoadHandler(new DefaultLoadHandler() {
    @Override
    public boolean onCertificateError(CertificateErrorParams params) {
        // Return false to ignore certificate error.
        return false;
    }
});

Verifying Certificate

In JxBrowser 6.3 the CertificateVerifier API has been introduced. Using this API you can get information about each SSL certificate used for displaying HTTPS web pages and decide whether it should be accepted or rejected. By default, Chromium engine decides whether certificate should be accepted/rejected.

You can register your own CertificateVerifier implementation to modify default behavior. For example:

NetworkService networkService = browser.getContext().getNetworkService();
networkService.setCertificateVerifier(new CertificateVerifier() {
    @Override
    public CertificateVerifyResult verify(CertificateVerifyParams params) {
        // Reject SSL certificate for all "google.com" hosts.
        if (params.getHostName().contains("google.com")) {
            return CertificateVerifyResult.INVALID;
        }
        return CertificateVerifyResult.OK;
    }
});

Network Events

JxBrowser provides functionality that allows handling network activity including HTTP requests/responses. You can use the NetworkDelegate to handle all network activity of the Browser instances associated with specified BrowserContext.

With NetworkDelegate you can intercept all HTTP requests/responses headers and obtain information about each request/response stage. Below is the list of all request/response stages:

onBeforeRequest

Fires when a request is about to occur. This event is sent before any TCP connection is made and can be used to redirect requests to another location. It can be used to access and modify POST data of the request when method type is “POST”. See example.

onBeforeSendHeaders

Fires when a request is about to occur and the initial headers have been prepared. It allows adding, modifying, and deleting HTTP request headers

onBeforeSendProxyHeaders

Fires after onBeforeSendHeaders when proxy connection is used. Provides information about proxy connection, and allows adding, modifying, and deleting HTTP request headers.

onSendHeaders

Fires right before the HTTP headers are sent to the network. This event is informational and it does not allow modifying HTTP headers.

onHeadersReceived

Fires each time that an HTTP(S) response header is received. Due to redirects and authentication requests this can happen multiple times per request. This event is intended to allow adding, modifying, and deleting HTTP response headers, such as incoming Set-Cookie headers.

onAuthRequired

Fires when a request receives an authentication challenge and is unable to respond using cached credentials. You can use this method to handle “basic” or “digest” authentication.

onBeforeRedirect

Fires when a request is about to occur and the initial headers have been prepared. It allows adding, modifying, and deleting HTTP request headers.

onResponseStarted

Fires when the first byte of the response body is received. For HTTP requests, this means that the status line and response headers are available. This event is informational.

onCompleted

Fires when a request has been processed successfully or failed.

onDestroyed

Fires when a request is being destroyed.

onCanSetCookies

Fires when engine is about to decide whether specified cookies can be set or not.

onCanGetCookies

Fires when engine is about to decide whether specified cookies can be received and send to a web server.

Accessing HTTP Response Data

JxBrowser API provides functionality that allows accessing HTTP response data such as HTML, plain text, JavaScript code, CSS, images, etc. Using this functionality you can capture AJAX response body content with information about its mime type. The following sample demonstrates how to use this functionality to access text/html data of each response:

networkService.setNetworkDelegate(new DefaultNetworkDelegate() {
    @Override
    public void onDataReceived(DataReceivedParams params) {
        if (params.getMimeType().equals("text/html")) {
            String data = new String(params.getData(),
                    Charset.forName("UTF-8"));
            System.out.println("data = " + data);
        }
    }
});

Protocol Handler

JxBrowser 6.11 and higher provides the API that allows you to handle URL requests for standard (e.g. HTTP, HTTPS, FTP, etc.) and non-standard (e.g. JAR, MYPROTOCOL, etc.) protocols. The following example demonstrates how to register protocol handler for standard HTTPS protocol and response with custom data:

import com.teamdev.jxbrowser.chromium.*;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

import javax.swing.*;
import java.awt.*;

public class ProtocolHandlerSample {
    public static void main(String[] args) {
        Browser browser = new Browser();
        BrowserView view = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(view, BorderLayout.CENTER);
        frame.setSize(700, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        BrowserContext browserContext = browser.getContext();
        ProtocolService protocolService = browserContext.getProtocolService();
        protocolService.setProtocolHandler("https", new ProtocolHandler() {
            @Override
            public URLResponse onRequest(URLRequest request) {
                URLResponse response = new URLResponse();
                String html = "<html><body><p>Hello there!</p></body></html>";
                response.setData(html.getBytes());
                response.getHeaders().setHeader("Content-Type", "text/html");
                return response;
            }
        });

        browser.loadURL("https://google.com/");
    }
}

You can use the same way to handle custom non-standard protocols (e.g. “teamdev”). For example:

import com.teamdev.jxbrowser.chromium.*;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

import javax.swing.*;
import java.awt.*;

public class ProtocolHandlerSample {
    public static void main(String[] args) {
        Browser browser = new Browser();
        BrowserView view = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(view, BorderLayout.CENTER);
        frame.setSize(700, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        BrowserContext browserContext = browser.getContext();
        ProtocolService protocolService = browserContext.getProtocolService();
        protocolService.setProtocolHandler("teamdev", new ProtocolHandler() {
            @Override
            public URLResponse onRequest(URLRequest request) {
                URLResponse response = new URLResponse();
                String html = "<html><body><p>Hello there!</p></body></html>";
                response.setData(html.getBytes());
                response.getHeaders().setHeader("Content-Type", "text/html");
                return response;
            }
        });

        browser.loadURL("teamdev://custom-request/");
    }
}

It is also possible to register a custom protocol handler for JAR protocol. It allows you to load HTML files directly from JAR libraries included into your application class path:

import com.teamdev.jxbrowser.chromium.*;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

import javax.swing.*;
import java.awt.*;
import java.io.DataInputStream;
import java.io.InputStream;
import java.net.URL;

public class ProtocolHandlerSample {
    public static void main(String[] args) {
        final Browser browser = new Browser();
        BrowserView view = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(view, BorderLayout.CENTER);
        frame.setSize(700, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        BrowserContext browserContext = browser.getContext();
        ProtocolService protocolService = browserContext.getProtocolService();
        protocolService.setProtocolHandler("jar", new ProtocolHandler() {
            @Override
            public URLResponse onRequest(URLRequest request) {
                try {
                    URLResponse response = new URLResponse();
                    URL path = new URL(request.getURL());
                    InputStream inputStream = path.openStream();
                    DataInputStream stream = new DataInputStream(inputStream);
                    byte[] data = new byte[stream.available()];
                    stream.readFully(data);
                    response.setData(data);
                    String mimeType = getMimeType(path.toString());
                    response.getHeaders().setHeader("Content-Type", mimeType);
                    return response;
                } catch (Exception ignored) {}
                return null;
            }
        });

        // Assume that we need to load a resource related to this class in the JAR file
        browser.loadURL(ProtocolHandlerSample.class.getResource("index.html").toString());
    }

    private static String getMimeType(String path) {
        if (path.endsWith(".html")) {
            return "text/html";
        }
        if (path.endsWith(".css")) {
            return "text/css";
        }
        if (path.endsWith(".js")) {
            return "text/javascript";
        }
        return "text/html";
    }
}

Modifying Upload Data

JxBrowser API provides functionality that allows accessing and modifying POST/PUT/PATCH upload data before it will be sent to a web server. POST/PUT/PATCH upload data can be one of the following types:

  • PLAIN_TEXT
  • BYTES
  • FORM_URL_ENCODED
  • MULTIPART_FORM_DATA

Depending on the upload data type, you can use different strategies for accessing and modifying upload data. The following sample demonstrates how to do this:

import com.teamdev.jxbrowser.chromium.*;
import com.teamdev.jxbrowser.chromium.swing.DefaultNetworkDelegate;

/**
 * This sample demonstrates how to read and modify POST data of
 * HTTP request using NetworkDelegate.
 */
public class POSTDataSample {
    public static void main(String[] args) {
        Browser browser = new Browser();
        BrowserContext browserContext = browser.getContext();
        NetworkService networkService = browserContext.getNetworkService();
        networkService.setNetworkDelegate(new DefaultNetworkDelegate() {
            @Override
            public void onBeforeURLRequest(BeforeURLRequestParams params) {
                if ("POST".equals(params.getMethod())) {
                    UploadData uploadData = params.getUploadData();
                    UploadDataType dataType = uploadData.getType();
                    if (dataType == UploadDataType.FORM_URL_ENCODED) {
                        FormData data = (FormData) uploadData;
                        data.setPair("key1", "value1", "value2");
                        data.setPair("key2", "value2");
                    } else if (dataType == UploadDataType.MULTIPART_FORM_DATA) {
                        MultipartFormData data = (MultipartFormData) uploadData;
                        data.setPair("key1", "value1", "value2");
                        data.setPair("key2", "value2");
                        data.setFilePair("file3", "C:\\Test.zip");
                    } else if (dataType == UploadDataType.PLAIN_TEXT) {
                        TextData data = (TextData) uploadData;
                        data.setText("My data");
                    } else if (dataType == UploadDataType.BYTES) {
                        BytesData data = (BytesData) uploadData;
                        data.setData("My data".getBytes());
                    }
                    // Apply modified upload data that will be sent to a web server.
                    params.setUploadData(uploadData);
                }
            }
        });
        browser.loadURL(new LoadURLParams("http://localhost/", "key=value"));
    }
}
Go Top