java 改造:如何等待响应

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

Retrofit: How to wait for response

javaandroidretrofit

提问by neustart47

I have AsyncTask and the doInBackground method inside which, I sending POST request using Retrofit. My code looks like:

我有 AsyncTask 和 doInBackground 方法,我在其中使用 Retrofit 发送 POST 请求。我的代码看起来像:

    //method of AsyncTask
    protected Boolean doInBackground(Void... params) {
        Retrofit restAdapter = new Retrofit.Builder()
                .baseUrl(Constants.ROOT_API_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        IConstructSecureAPI service = restAdapter.create(IConstructSecureAPI.class);
        //request
        Call<JsonElement> result = service.getToken("TestUser", "pass", "password");
        result.enqueue(new Callback<JsonElement>() {
            @Override
            public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {

            }

            @Override
            public void onFailure(Call<JsonElement> call, Throwable t) {

            }
        });

        return true;
    }

The problem is: Retrofit sending request asynchronously and while it, the doInBackground method returning the value. So I need to send a request in the same thread with all executions in the sequence. One by one. And returning from doInBackground occurs after the request finished. How can I send a request in the same thread using Retrofit?

问题是:改造异步发送请求,同时 doInBackground 方法返回值。所以我需要在同一个线程中发送一个请求,并按顺序执行所有操作。逐个。并且在请求完成后从 doInBackground 返回。如何使用 Retrofit 在同一线程中发送请求?

回答by Bryan Herbst

The Callclass has an execute()method that will make your call synchronously.

Call类有一个execute()方法,这将使你的电话同步。

enqueue()is explicitly for making an asychronous call.

enqueue()明确用于进行异步调用。

回答by Emma

"Retrofit sending request asynchronously" which as @Tanis.7x mentioned, enqueue() is doing the asynchronous, so what could be a reason to put in AsyncTask ? (async in async ?)

正如@Tanis.7x 提到的“异步改造发送请求”, enqueue() 正在执行异步操作,那么放入 AsyncTask 的原因是什么?(异步中的异步?)

You can simply put all retrofit code out from AsyncTask and onResponseis the callback that is waiting for your request call to be back, so you can do any UI update inside of this callback.

您可以简单地从 AsyncTask 中取出所有改造代码,并且onResponse是等待您的请求调用返回的回调,因此您可以在此回调中执行任何 UI 更新。