Monday, November 28, 2022

Intercept Network Requests in a React Native App



React Native is development framework enabling development of applications for both Android and iOS using the same react like code base. It provides fast development for JavaScript engineers, and reduces the need to learn both iOS and Android proprietary development method and tools.

Most apps do not stand on their own, and need to send network requests to a server. In many cases, intercepting these requests from within the app, and adding/changing some of the requests has a real value, for example, handling authentication, adding tracking info, and more.

 In this post we will present how to intercept network requests in a React Native app. We will start by creation of a new React Native app, then add a sample network request from the app, and finally, we will learn to intercept the network requests.


Create a New React Native App

To create a new React Native app, run the following:

npx react-native init MyTestApp
cd MyTestApp


Then run these commands.
Each command should run in a different terminal (in the MyTestApp folder).

Terminal 1:
npx react-native start

Terminal 2:
npx react-native run-android

Send a Network Request

First install axios:

npm install -S axios

Add a call upon onPress on any element to axios:

async function apiCall() {
 const axiosInstance = axios.create({
   baseURL: 'http://www.my-server.com/',
   headers: {
     'Cache-Control': 'max-age=640000',
     'User-Agent': 'MyApp',
   },
 });

 axiosInstance.get('index.html').then(response => {
   console.log(response.data);
 });
}

Intercept Network Requests

In android/app/build.gradle under dependencies section, add:

implementation 'androidx.appcompat:appcompat:1.4.0'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'


In the MainApplication.java 

import com.facebook.react.modules.network.OkHttpClientProvider;

And in the onCreate method:

OkHttpClientProvider.setOkHttpClientFactory(new InterceptorClient());

Lastly, implement the Interceptor intself:


import com.facebook.react.modules.network.OkHttpClientFactory;

import okhttp3.OkHttpClient;
import okhttp3.Request;

public class InterceptorClient implements OkHttpClientFactory {

    @Override
    public OkHttpClient createNewNetworkModuleClient() {
        return new OkHttpClient.Builder()
                .addInterceptor(chain -> {
                    Request original = chain.request();
                    Request.Builder builder = original.newBuilder()
                            .addHeader("My-authenticatoin", "my-token");
                    Request request = builder.build();

                    return chain.proceed(request);
                })
                .build();
    }
}




No comments:

Post a Comment