英文:
Null Response with okhttp3
问题
以下是你提供的代码的翻译部分:
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;
}
}
希望对你有所帮助。
英文:
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
答案1
得分: 0
你应该重用客户端,并且使用同步形式的 execute
方法,而不是使用回调 API 的异步形式,后者会在请求完成之前几乎立即返回。
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();
}
}
}
英文:
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();
}
}
}
专注分享java语言的经验与见解,让所有开发者获益!
评论