简体   繁体   中英

Null Response with okhttp3

so I coded this class to Download URLs but it's returning Null Response I tried to debug but didn't understand anything

package com.example.instaup;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Downloader
{
    private String myResponse;

    public String DownloadText(String url)
    {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(url)
                    .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()) {
                        myResponse = response.body().toString();
                    }
                }
            });
        return myResponse;
    }
}

Can Someone Help me? I'm kinda new to this

You should reuse the client, and use the synchronous form execute instead of the enqueue callback API which returns almost immediately before the request has finished.

import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Downloader {
  OkHttpClient client = new OkHttpClient();

  public String DownloadText(String url) throws IOException {
    Request request = new Request.Builder().url(url).build();
    try (Response myResponse = client.newCall(request).execute()) {
      return myResponse.body().string();
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM