【问题标题】:Android - OkHTTP requestsAndroid - OkHTTP 请求
【发布时间】:2016-09-17 22:52:28
【问题描述】:

我正在使用 HttpUrlConnection 使用 Web 服务向我的 mysql 数据库发出请求。使用 HttpUrlConnection,我可以在后台执行所有请求,这样主线程就不会超载并开始跳帧。

使用okHttp是如何实现的呢?如何使用它发出请求并使用 JSON 打印响应?比httpUrlConnection好吗?

P.S 我对 okHttp 一无所知,如果您能明确说明您的示例,我将不胜感激。

【问题讨论】:

    标签: android web-services httpurlconnection okhttp3


    【解决方案1】:

    使用okHttp是如何实现的呢?

    通常,您让它为您处理后台线程,使用enqueue() 进行异步操作:

      private final OkHttpClient client = new OkHttpClient();
    
      public void run() throws Exception {
        Request request = new Request.Builder()
            .url("http://publicobject.com/helloworld.txt")
            .build();
    
        client.newCall(request).enqueue(new Callback() {
          @Override public void onFailure(Call call, IOException e) {
            // handle the error
          }
    
          @Override public void onResponse(Call call, Response response) throws IOException {
              // use the result
          }
        });
      }
    

    (从the OkHttp docs略微简化)

    或者,如果您已经有后台线程,则可以使用execute() 代替enqueue() 进行同步操作。

    您可能希望查看 the OkHttp recipes pagethe OkHttp Web pagethe OkHttp wiki 上的其他示例,以便更好地了解它与您习惯的比较。

    【讨论】:

    • 考虑使用 okhttp 进行改造,让整个事情变得更简单。
    猜你喜欢
    • 1970-01-01
    • 2019-04-12
    • 1970-01-01
    • 2020-06-21
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 2020-03-28
    • 2019-08-27
    相关资源
    最近更新 更多