【问题标题】:How to use OKHTTP in main java如何在主java中使用OKHTTP
【发布时间】:2015-11-10 00:19:37
【问题描述】:

这是 okhttp 中的简单 GET 方法:

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

我把这段代码放在主 java 文件中。

那么我应该在哪里调用它到 onCreate 方法中呢?

我不知道如何使用它。例如,我想在按钮的 onclicklistener 中使用它。

【问题讨论】:

  • 比如我想在一个按钮的onclicklistener中使用它。那你为什么不把代码放在那里呢?
  • @TimCastelijns 我收到错误消息。我曾经使用没有功能的请求,但在 logcat 和死应用程序中仍然出现错误。
  • 那么,错误是什么? NetworkOnMainThreadException?
  • @TimCastelijns 是的。我认为它需要一个线程。是吗?
  • 是的,你不能在主线程上使用网络,你需要使用 AsyncTask 或类似的东西。谷歌一下,你会找到答案

标签: java android http okhttp


【解决方案1】:

如果您使用 eclipse,则必须下载 okHttp jar 文件并将其包含在您的项目中;如果您使用 android studio,则必须在 build.gradle 中添加依赖项。你可以在这里找到说明 - http://square.github.io/okhttp/

最好为网络创建一个通用的 Util 类并编写通用方法 HTTP 请求(GET、POST 等),以便可以通过传递所需的参数从应用程序中的任何位置调用它们。

现在,如果您愿意,可以将其添加到 onclicklistener

示例 -

public class GetExample {
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();
}

public static void main(String[] args) throws IOException {
GetExample example = new GetExample();
String response = example.run("https://raw.github.com/square/okhttp/master/README.md");
System.out.println(response);
}
}

对于 onClickListener,你可以在 AsyncTask 或 new Thread 中编写以下代码(希望你知道如何编写 AsyncTask 或 new Thread )-

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

Response response = client.newCall(request).execute();
String reponse = response.body().string();

【讨论】:

  • 谢谢。我应该在 onclicklistener 中写什么?
  • 已编辑答案,请检查
猜你喜欢
  • 2019-07-14
  • 2021-02-08
  • 1970-01-01
  • 1970-01-01
  • 2016-07-12
  • 1970-01-01
  • 1970-01-01
  • 2017-02-26
  • 2016-01-06
相关资源
最近更新 更多