Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use my own OkHttp client in react-native (0.54 + )

My images and a number of other functions are sitting behind my backend APIs (written with java spark framework). The services are https only, and APIs are often performing additional functions (eg they are not just serving static images).

In React-native javascript forms, I do

const imageTest='https://10.0.1.10:4567/api/v1/get-image-simple/full-size/myImage.jpg/'


            <Image source={{uri : imageTest}} 
                   style={theme.cardImageStyle}
            />

This does not work because my server uses self-signed certificates (and also requires some explicit headers).

Same kinds of image urls link, work fine from within my android host (my app is a hybrid some activities are android only, some are with react native). My android app has custom okhttp client with all the necessary settings, to communicate to my apis via HTTPs.

I cannot find an example/reference of how to hook my OkHTTP client into react native, so that everything goes through there. I had seen various bug reports like this, but cannot seem to find any documentation of what's actually in the react-native releases.

I tried, blindly, do

com.facebook.react.modules.network.OkHttpClientProvider.replaceOkHttpClient(
                    MyPersonalAppInstance.getApplicationComponent().okHttpClient());

but it does not seem to do anything;

like image 553
V P Avatar asked Apr 08 '18 21:04

V P


1 Answers

I've not had a chance to test this out, but according to the discussion on [this issue][1], the following should work in 0.54+ to set a custom OkHttp client.

Create React Native application and set a custom factory in the constructor, e.g. OkHttpClientProvider.setOkHttpClientFactory(new CustomNetworkModule());

Where a custom factory would look like:

class CustomNetworkModule implements OkHttpClientFactory {
    public OkHttpClient createNewNetworkModuleClient() {
        return new OkHttpClient.Builder()
                        .cookieJar(new ReactCookieJarContainer())
                        .build();
    }
}

The above is based on info from this commit.

like image 56
iagreen Avatar answered Nov 04 '22 11:11

iagreen