如果每个请求都有一个改造实例会发生什么? [英] What will happen if every request has a retrofit instance?

查看:57
本文介绍了如果每个请求都有一个改造实例会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在想一个问题.

如果每个请求都有一个改造实例,会发生什么?

我希望每个请求都有一个改造实例的原因:

The reason I want every request has a retrofit instance:

每个改造实例都有一个OkHttpClient实例,所以我想添加拦截到OkhttpClient,但不是每个请求都应该拦截,我还想向 OkHttpClient 添加一些相同的标头,但并非每个请求都必须具有这些相同的标头>,就像登录请求时,我不需要添加令牌.但其他请求可能需要.

Every retrofit instance has an OkHttpClient instance,so I want add Interception to OkhttpClient,but not every request should be intercepted,and I also want to add some same headers to OkHttpClient,but not every request must has these same headers,like when it's login request,I don't need add token.,but other request may need.

所以我的方式是让每一个请求都有一个改造实例,我之前有一个demo,但是请求的数量很少,所以我不确定是否当请求过多出问题吗?

So my way is to let every request has a retrofit instance,I have a demo before,but the quantity of requests are few,So I am not sure whether when there are too many requests will it come trouble?

我有两个问题:

1.会产生一些异常吗?还是会造成堆栈溢出?

1. Will it make some exceptions?Or Will it make stack overflow?

2.如果有更好的方法来解决这个问题?

2. If there is some better way to solve the question?

有其他人有同样的经历或有一些想法要质疑吗?

推荐答案

您可以使用 @Headers 批注为 Retrofit 添加静态/动态标头.此外,您不应该按照文档中的说明创建单独的 OkHttp 实例:

You can use @Headers annotation to add static/dynamic header to Retrofit. Moreover, you shouldn't create separate OkHttp instance as stated in documentation:

当您创建单个 OkHttpClient 实例并将其重用于所有 HTTP 调用时,OkHttp 的性能最佳.这是因为每个客户端都拥有自己的连接池和线程池.重用连接和线程可减少延迟并节省内存.相反,为每个请求创建一个客户端会浪费空闲池上的资源.

OkHttp performs best when you create a single OkHttpClient instance and reuse it for all of your HTTP calls. This is because each client holds its own connection pool and thread pools. Reusing connections and threads reduces latency and saves memory. Conversely, creating a client for each request wastes resources on idle pools.

如果您想为每个 OkHttp 设置不同的配置,只需使用 client.newBuilder()(从 3.x 版开始可用):

If you want different configuration for each OkHttp just use client.newBuilder() (available from version 3.x):

您可以使用 newBuilder() 自定义一个共享的 OkHttpClient 实例.这将构建一个共享相同连接池、线程池和配置的客户端.使用构建器方法为特定目的配置派生客户端.

You can customize a shared OkHttpClient instance with newBuilder(). This builds a client that shares the same connection pool, thread pools, and configuration. Use the builder methods to configure the derived client for a specific purpose.

如果 @Headers 不适合您,只需创建尽可能多的 OkHttpClient 配置,以创建不同的 Retrofit 服务,然后您会好的.

If @Headers is not suitable for you, just create as many configurations of OkHttpClient as you want to create different Retrofit services and you will be ok.

http://square.github.io/okhttp/3.x/okhttp/

这篇关于如果每个请求都有一个改造实例会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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