改造:如何等待回应

neu*_*t47 9 java android retrofit

我有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;
    }
Run Code Online (Sandbox Code Playgroud)

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

Tan*_*.7x 14

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

enqueue() 明确表示要进行异步调用.

  • 是的,但是因为execute()是同步的,所以它似乎正在主线程上运行。在这种情况下,execute()是正确的答案,因为发布者已经在后台线程上工作,并且execute()将在该线程上。 (2认同)