OKHttp:帮助理解"run"或"post"的"stray"方法?

OKHttp: Help understanding the "stray" method of "run" or "post"?

我一直在查看 OkHttp 中的示例 android,我注意到定义了 2 种方法,一种称为 "run",另一种称为 "post",但它们似乎从来没有叫做。有什么负责调用这些的吗?他们怎么称呼。

或者这些只是标准方法,作为我可以更改的示例显示?

这是示例中的一个片段,显然我没有完全理解它,因为它们看起来像 "stray" 方法,没有人调用它们

这里是 "run"

OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
  Request request = new Request.Builder()
      .url(url)
      .build();

  Response response = client.newCall(request).execute();
  return response.body().string();
}

这里的另一个片段是 "post",我没有看到任何对它的引用

public static final MediaType JSON
      = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();
}

谁能解释一下背后的原因?

谢谢。

这些方法将对给定的 URL 执行请求。

你只需要这样称呼他们:

OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
  Request request = new Request.Builder()
      .url(url)
      .build();

  Response response = client.newCall(request).execute();
  return response.body().string();
}

String response = run("http://www.url.com");

此外,您可以将他们的名字更改为任何名称。没关系。

这段代码最重要的部分是:

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
    .url(url)
    .build();

Response response = client.newCall(request).execute();

您可以使用 response 对象来获取 responseCoderesponseBodyHeaders