Network Options (Mobile)

This page describes how to intercept and sanitize network requests and responses using the OpenReplay Mobile SDKs for iOS and Android. Capturing network data can help developers understand and troubleshoot issues effectively.

iOS SDK - Intercepting the Network

Section titled iOS SDK - Intercepting the Network

The iOS SDK provides a NetworkListener class to capture network requests and responses, including headers and payloads. Here is how you can use it:

import ORTracker

func fetchPokemonData(for name: String) {
    let networkListener = NetworkListener()
    let url = URL(string: "https://pokeapi.co/api/v2/pokemon/ditto")!
    var request = URLRequest(url: url)
    request.httpMethod = "GET" // This is the default, so it's optional in this case.

    // Start the network listener with the request
    networkListener.start(request: request)

    // Create a data task
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        if let error = error {
            print("Error: \(error.localizedDescription)")
            return
        }
        
        if let data = data {
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                print(json)
            } catch {
                print("Error deserializing JSON: \(error)")
            }
        }
        
        networkListener.finish(response: response, data: data)
    }

    task.resume()
}

You can sanitize request and response data by defining ignored keys for JSON bodies and ignored headers. Both request and response sanitization are supported. The body sanitization applies only to valid JSON payloads.

let networkListener = NetworkListener()
networkListener.ignoredHeaders = ["mySecretToken"]
networkListener.ignoredKeys = ["password"]

To modify the response data before passing it to the listener:

var sanitizedData
if let data = data {
    do {
        let json = try JSONSerialization.jsonObject(with: data, options: [])
        sanitizedData = customSanitizeFunction(data)
        print(json)
    } catch {
        print("Error deserializing JSON: \(error)")
    }
}

networkListener.finish(response: response, data: sanitizedData)

Android SDK - Intercepting the Network

Section titled Android SDK - Intercepting the Network

The Android SDK also provides a NetworkListener class for capturing network requests and responses. Here is an example implementation:

import com.openreplay.tracker.NetworkListener;

public void makeSampleRequest() {
    new Thread(() -> {
        try {
            URL url = new URL("https://jsonplaceholder.typicode.com/posts/1");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            // Optionally set request headers
            connection.setRequestProperty("Content-Type", "application/json");

            // Initialize the network listener for this connection
            NetworkListener networkListener = new NetworkListener(connection);

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            // Using the network listener to log the finish event
            networkListener.finish(connection, response.toString().getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }).start();
}

Similar to the iOS SDK, the Android SDK allows you to sanitize request and response data by defining ignored keys for JSON bodies and ignored headers.

NetworkListener networkListener = new NetworkListener(connection);
networkListener.setIgnoredHeaders(Arrays.asList("mySecretToken"));
networkListener.setIgnoredKeys(Arrays.asList("password"));

To modify the response data before passing it to the listener:

String sanitizedData = null;
if (responseData != null) {
    sanitizedData = customSanitizeFunction(responseData);
}

// Pass the sanitized data to the NetworkListener
if (sanitizedData != null) {
    networkListener.finish(connection, sanitizedData.getBytes());
} else {
    networkListener.finish(connection, new byte[0]); // Handle cases where sanitized data is null
}

If you have any questions about sanitizing network requests, feel free to reach out to us on our Slack or check out our Forum.