java Android 如何使用 OkHttp 从回调中获取响应字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31145811/
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-11-02 18:10:56  来源:igfitidea点击:

Android how to get response string from Callback using OkHttp?

javaandroidokhttp

提问by tm-null

This is my code:

这是我的代码:

    OkHttpClient okHttpClient = new OkHttpClient();

    Request request = new Request.Builder().url("http://publicobject.com/helloworld.txt").build();

    Callback callback = new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {

        }

        @Override
        public void onResponse(Response response) throws IOException {

        }
    };

    okHttpClient.newCall(request).enqueue(callback);

    String responseString;

In the above code, I want to store the value of response.body().string() from the onResponse() method in the variable responseString, however I can't access it.

在上面的代码中,我想将 onResponse() 方法中 response.body().string() 的值存储在变量 responseString 中,但是我无法访问它。

采纳答案by Matt Wolfe

I think what you want to do is something like this:

我认为你想做的是这样的:

public class MyActivity extends Activity implements Callback , View.OnClickListener {


 @Override
 public void onCreate(Bundle savedState) {
   super.onCreate(savedState);
   findViewById(R.id.DoHttp).setOnClickListener(this);
 } 

 @Override
 public void onClick(View v) {
   if (v.getId(() == R.id.DoHttp) {

     OkHttpClient okHttpClient = new OkHttpClient();

     Request request = new Request.Builder().url("http://publicobject.com/helloworld.txt").build();
     okHttpClient.newCall(request).enqueue(this);
   }
 }


 @Override
 public void onFailure(Request request, IOException e) {
  //do something to indicate error
 }

  @Override
  public void onResponse(Response response) throws IOException {
    if (response.isSuccessful()) {
     parse(response.body().string());
    }
  }

  private void parse(String response) {
   //do something with response
  } 
}

In the above activity we implement Callback and then when we create the okhttp request, we pass it an instance of ourself (this) and that way we can get oktthp to call back the class, we could have done an inner class just as easily but this reduces the # of classes we have to make. I used a button click to illustrate when the Http call is made but that could be some other time, for instance it could happen when the screen is first created (in onCreate). Be careful though of screen rotations. Also this assumes that the callback is done on the main thread which I think it would be but I'm not positive as I use okttp in a different way than you. If it does not return the results on the response on the main thread then you can call runOnUiThread() and pass it a Runnable that does the work of updating the views.

在上面的活动中,我们实现了回调,然后当我们创建 okhttp 请求时,我们将我们自己的实例(this)传递给它,这样我们就可以让 oktthp 回调该类,我们可以很容易地完成一个内部类,但是这减少了我们必须创建的类的数量。我使用按钮单击来说明何时进行 Http 调用,但这可能是其他时间,例如它可能在首次创建屏幕时(在 onCreate 中)发生。小心屏幕旋转。此外,这假设回调是在主线程上完成的,我认为这会是,但我并不乐观,因为我使用 okttp 的方式与您不同。如果它没有在主线程上返回响应结果,那么您可以调用 runOnUiThread() 并将其传递给执行更新视图工作的 Runnable。

回答by David Argyle Thacker

If you move the responseStringdeclaration to be an instance variable then you will be able to assign its value in the onResponsemethod of your Callback.

如果您将responseString声明移动为实例变量,那么您将能够在onResponse您的Callback.

public class MyClass {

    private String responseString; 

    // your class implementation

}

I have modified the code you posted with the necessary changes below:

我已经修改了您发布的代码,并进行了以下必要的更改:

OkHttpClient okHttpClient = new OkHttpClient();

Request request = new Request.Builder().url("http://publicobject.com/helloworld.txt").build();

Callback callback = new Callback() {
    @Override
    public void onFailure(Request request, IOException e) {

    }

    @Override
    public void onResponse(Response response) throws IOException {
        responseString = response.body().string();
    }
};

okHttpClient.newCall(request).enqueue(callback);

回答by Tomek

First answer is close, but you cannot assign final variable in method onResponse. Workaround is to type final String[] responseString = new String[1];and assign responseString[0] = response.body().string();

第一个答案很接近,但您不能在方法 onResponse 中分配最终变量。解决方法是键入final String[] responseString = new String[1];和分配responseString[0] = response.body().string();