OkHttp在android中用于发出网络请求 [英] OkHttp in android for making network requests

查看:187
本文介绍了OkHttp在android中用于发出网络请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做什么 ::

我正在尝试学习 Okhttp 在Android中进行网络通话

I am trying to learn the usage of Okhttp for making networking calls in android

我做了什么 ::


  • 我已阅读他们的文档 此处

  • 我已下载并在项目中添加了JAR

  • 我正在使用 here

  • I have read their documentation here
  • I have downloaded and added the JAR in the project
  • I am using their sample code from here

MyCode ::

MainActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.internal.http.Request;
import com.squareup.okhttp.internal.http.Response;
    public class MainActivity extends Activity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

             Request request = new Request.Builder()
                .url("https://raw.github.com/square/okhttp/master/README.md")
                .build();

            Response response = client.execute(request);

            Log.d("ANSWER", response.body().string());

        }

    }






我正面临的错误 ::

响应响应=客户端。执行(请求);
我收到错误:

In the line Response response = client.execute(request); I am getting error as :


客户端无法解析变量

client cannot resolved to a variable

如何解决这个问题!

public class MainActivity extends Activity {

    OkHttpClient client = new OkHttpClient();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

         Request request = new Request.Builder()
            .url("https://raw.github.com/square/okhttp/master/README.md")
            .build();

        Response response = client.execute(request);

        Log.d("ANSWER", response.body().string());

    }

}

现在我是面临错误:

行中的

响应响应= client.execute(请求); as 方法execute(Request)未定义类型OkHttpClient


推荐答案


方法执行(请求)未定义类型OkHttpClient

The method execute(Request) is undefined for the type OkHttpClient

您收到此异常是因为没有这样的方法,即执行(请求 OkHttpClient 。而是在调用对象上调用,该对象是使用 OkHttpClient 对象获得的,如下所示:

You are getting this exception because there is no such method ie.execute(Request) for OkHttpClient. Rather it is invoked on Call object which is obtained using OkHttpClient object as follows:

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

我认为你应该使用

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

而不是响应响应= client.execute(请求);

OkHttp docs

OkHttp Blog

这篇关于OkHttp在android中用于发出网络请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆