【问题标题】:How Retrofit works under the hoodRetrofit 如何在幕后工作
【发布时间】:2020-02-22 05:04:23
【问题描述】:

关于 Retrofit2 的问题:

在你构建一个 Retrofit 实例之后,你调用一个接口(客户端)方法来“发送请求”

例如,如果您有这样的界面:

@POST("webhook.php")
Call<String>  queueCustomer(@Body String queue);

以及您使用 create 方法创建的“客户端”的 Retrofit 实例,然后您可以这样调用它:

client.queueCustomer(someString)

我假设这实际上是在发出网络请求。但是,您获取由此返回的 Call 对象并调用如下内容:

callObject.enqueue(........)

您在调用 enqueue 时是否在发出后续网络请求?这是两个网络请求还是第一部分:client.queueCustomer(someString) 只是构造将通过callObject.enqueue(........) 发送的对象?

提前致谢

【问题讨论】:

  • 你可以在这里找到完整的源代码github.com/square/retrofit
  • client.queueCustomer(someString) 为您提供 Call 对象。然后您可以使用 Call.enqueue() 或 Call.execute() 方法来发出请求。虽然 enqueue 方法是异步的,但执行是同步的。
  • @toffor 所以我在接口中定义的方法只是构造调用对象而不发出任何网络请求吧?

标签: android retrofit2


【解决方案1】:

当您设置改造实例并使用 Retrofit.create(ApiService::class.java) 创建服务时,然后使用代理类创建服务接口实现。下面是 Retrofit 类的代码块,它构造服务接口实现和调用对象。实际上,retrofit 是一个包装库,用于将接口转换为 OkHttp 调用。因此,当您调用接口方法时,它只会将您返回到相应的调用对象,但除非您运行 enqueue 或 execute 方法,否则它不会发出请求。

public <T> T create(final Class<T> service) {
    validateServiceInterface(service);
    return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
        new InvocationHandler() {
          private final Platform platform = Platform.get();
          private final Object[] emptyArgs = new Object[0];

          @Override public @Nullable Object invoke(Object proxy, Method method,
              @Nullable Object[] args) throws Throwable {
            // If the method is a method from Object then defer to normal invocation.
            if (method.getDeclaringClass() == Object.class) {
              return method.invoke(this, args);
            }
            if (platform.isDefaultMethod(method)) {
              return platform.invokeDefaultMethod(method, service, proxy, args);
            }
            return loadServiceMethod(method).invoke(args != null ? args : emptyArgs);
          }
        });
  }

【讨论】:

猜你喜欢
  • 2014-11-18
  • 2011-02-17
  • 2012-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-10
相关资源
最近更新 更多