OkHttp3 response.body (). String () всегда возвращает пустое - PullRequest
0 голосов
/ 04 мая 2020

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.io.Reader;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class MainActivity extends AppCompatActivity {

    TextView title;
    TextView instructions;

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

        title = findViewById(R.id.titleView);
        instructions = findViewById(R.id.instructionsView);

        OkHttpClient client = new OkHttpClient();

        String url = "https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/findByIngredients?number=1&ranking=1&ignorePantry=false&ingredients=apple%252Csugar%252Csalt";
        Request request = new Request.Builder()
                .url(url)
                .get()
                .addHeader("x-rapidapi-host", "spoonacular-recipe-food-nutrition-v1.p.rapidapi.com")
                .addHeader("x-rapidapi-key", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    String myResponse = response.body().string();
                    Log.i("string", myResponse);
                }
            }
        });
    }
}

Выход журнала для .toString (): 2020-05-04 19: 55: 51.801 9894-10024 / com.example.testapi I / string: okhttp3.internal.http. RealResponseBody@6314479

Вывод журнала для .string (): 2020-05-04 20: 00: 39.430 10118-10143 / com.example.testapi I / string: []

Я знаю о том, как пытается OkHttp3 очистить резервный ресурс, как только будет сделан первый вызов .body (), но он все еще для меня пуст.

Как я могу это исправить?

...