如何在react-native(0.54 +)中使用我自己的OkHttp客户端 [英] how to use my own OkHttp client in react-native (0.54 + )

查看:529
本文介绍了如何在react-native(0.54 +)中使用我自己的OkHttp客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的图像和许多其他功能都位于我的后端API(使用Java Spark框架编写)的背后.这些服务仅是https,并且API通常会执行其他功能(例如,它们不仅提供静态图像).

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).

在React本机javascript表单中,我这样做

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).

相同类型的图片url链接,可以在我的android主机内正常工作(我的应用是混合动力,有些活动仅是android,有些是带有react native的). 我的android应用具有自定义的okhttp客户端,该客户端具有所有必要的设置,可通过HTTPs与我的api通信.

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.

我找不到有关如何将OkHTTP客户端挂接到本机反应的示例/参考,以便所有内容都通过那里. 我见过各种错误报告,例如,但似乎找不到任何文档本机版本中的实际内容.

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.

我盲目地尝试做

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

但它似乎无能为力;

推荐答案

我没有机会对此进行测试,但是根据对[this issue][1]的讨论,以下内容应适用于0.54+的版本以设置自定义OkHttp客户端.

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.

创建React Native应用程序并在构造函数中设置自定义工厂,例如OkHttpClientProvider.setOkHttpClientFactory(new CustomNetworkModule());

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();
    }
}

以上内容基于此提交的信息.

这篇关于如何在react-native(0.54 +)中使用我自己的OkHttp客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆