Retrofit 如何在幕后工作

Jo *_*mma 4 android retrofit2

关于 Retrofit2 的问题:

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

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

@POST("webhook.php")
Call<String>  queueCustomer(@Body String queue);
Run Code Online (Sandbox Code Playgroud)

以及使用 create 方法创建的“client”的 Retrofit 实例,然后像这样调用它:

client.queueCustomer(someString)
Run Code Online (Sandbox Code Playgroud)

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

callObject.enqueue(........)
Run Code Online (Sandbox Code Playgroud)

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

提前致谢

tof*_*for 5

当您设置改造实例并使用 Retrofit.create(ApiService::class.java) 创建服务时,然后使用代理类创建服务接口实现。下面是来自 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);
          }
        });
  }
Run Code Online (Sandbox Code Playgroud)