Java android 中的 OkHttp 用于发出网络请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23201663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 21:18:07  来源:igfitidea点击:

OkHttp in android for making network requests

javaandroidokhttp

提问by Devrath

What I am trying to do::

我正在尝试做什么::

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

我正在尝试学习Okhttp在 android 中进行网络调用的用法



What I have done::

我做了什么::

  • I have read their documentation here
  • I have downloaded and added the JAR in the project
  • I am using their sample code from here
  • 在这里阅读了他们的文档
  • 我已经下载并在项目中添加了 JAR
  • 我从这里使用他们的示例代码


MyCode::

我的代码::

MainActivity.java

主活动.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());

        }

    }


Error i am facing::

我面临的错误::

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

在这一行中,Response response = client.execute(request);我收到以下错误:

client cannot resolved to a variable

客户端无法解析为变量

How to resolve this !

这个怎么解决!



{Update}

{更新}

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

    }

}

Now I am facing error as :

现在我面临的错误是:

in the line Response response = client.execute(request);as The method execute(Request) is undefined for the type OkHttpClient

在行Response response = client.execute(request);The method execute(Request) is undefined for the type OkHttpClient

采纳答案by Ritesh Gune

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

未定义类型 OkHttpClient 的方法 execute(Request)

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

您收到此异常是因为没有这样的方法,即。execute(Request) 为OkHttpClient。相反,它是在Call使用OkHttpClientobject获得的object上调用的,如下所示:

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

I think you should be using

我认为你应该使用

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

instead of Response response = client.execute(request);

代替 Response response = client.execute(request);

OkHttp docs

OkHttp 文档

OkHttp Blog

OkHttp博客

回答by rperryng

you are missing this line

你错过了这一行

OkHttpClient client = new OkHttpClient();

OkHttpClient client = new OkHttpClient();

回答by deleon

You need declare client variable like this:

您需要像这样声明客户端变量:

OkHttpClient client = new OkHttpClient();

Also you should use your request using some thread or AsyncTask!

此外,您应该使用一些线程或 AsyncTask 来使用您的请求!

You can read something else about AsyncTask on Android in this link: http://androidresearch.wordpress.com/2012/03/17/understanding-asynctask-once-and-forever/

您可以在此链接中阅读有关 Android 上 AsyncTask 的其他内容:http: //androidresearch.wordpress.com/2012/03/17/understanding-asynctask-once-and-forever/

回答by zapotec

I think you should use the new 2.0 RC of okHttp.

我认为您应该使用 okHttp 的新 2.0 RC。

To make a POST petition, the best is :

要进行 POST 请愿,最好是:

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

回答by user3801095

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

    new AsyncTask<String, Integer, String> (){

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
            try {
                client = new OkHttpClient();
                s = post("https://raw.github.com/square/okhttp/master/README.md","");
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            Log.e("ANSWER", "" + s);

        }
    }.execute();

}

回答by Droid_Mechanic

You only need to replace: This:

你只需要替换: 这个:

Response response = client.execute(request);

By:

经过:

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

回答by Gopi Cg

@Override
protected String doInBackground(String... ulr) {
    Response response = null;
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
    .url(ulr[0])
    .build();

    try {
        response = client.newCall(request).execute();
         return response.body().string();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;        
}

use like this!

像这样使用!

回答by Amit Garg

Try adding internet permissions in your manifest file?

尝试在清单文件中添加 Internet 权限?

<uses-permission android:name="android.permission.INTERNET" />