【发布时间】:2021-08-05 13:42:54
【问题描述】:
我遇到了改造问题: 我试图向这个 API 发出 get 请求:https://test.spaceflightnewsapi.net/api/v2/articles
但不知何故,改造中的回调方法没有被调用。 我在 logcat/ 中得到了这个唯一与改造相关的东西(okkhttp):
I/okhttp.OkHttpClient: --> GET https://test.spaceflightnewsapi.net/api/v2/articles
I/okhttp.OkHttpClient: --> END GET
这是我的api接口:
public interface SpaceNewsApi {
String BASE_URL = "https://test.spaceflightnewsapi.net/api/v2/";
@GET("articles")
Call<List<SpaceNews>> getSpaceNewsArticles();
}
这是改造客户端(请注意,我将使用两个 api 进行改造,这就是为什么我使用两种方法来构建它),我还添加了一个日志拦截器,我已经将级别更改为不同类型,但只有上面的内容是我每次在与改造相关的日志中收到的消息
public class RetrofitClients {
private static RetrofitClients instance = null;
private SpaceNewsApi mySpaceNewsApi = null;
private LaunchLibraryApi myLaunchLibraryApi = null;
public static synchronized RetrofitClients getInstance() {
if (instance == null) {
instance = new RetrofitClients();
}
return instance;
}
public SpaceNewsApi getMySpaceNewsApi() {
if(mySpaceNewsApi == null) {
Retrofit retrofit = new Retrofit.Builder().baseUrl(SpaceNewsApi.BASE_URL)
.client(getHttpClient())
.addConverterFactory(GsonConverterFactory.create())
.build();
mySpaceNewsApi = retrofit.create(SpaceNewsApi.class);
}
return mySpaceNewsApi;
}
public LaunchLibraryApi getMyLaunchLibraryApi(){
if(myLaunchLibraryApi == null) {
Retrofit retrofit = new Retrofit.Builder().baseUrl(LaunchLibraryApi.BASE_URL)
.client(getHttpClient())
.addConverterFactory(GsonConverterFactory.create())
.build();
myLaunchLibraryApi = retrofit.create(LaunchLibraryApi.class);
}
return myLaunchLibraryApi;
}
public static OkHttpClient getHttpClient() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.HEADERS);
//TODO : remove logging interceptors as it is to be used for development purpose
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(300, TimeUnit.SECONDS)
.readTimeout(300, TimeUnit.SECONDS)
.addInterceptor(logging)
.build();
return client;
}
}
我在我的主要活动 onCreate 方法中调用所有这些,如下所示:
//testing Api Call
Call<List<SpaceNews>> call = RetrofitClients.getInstance().getMySpaceNewsApi().getSpaceNewsArticles();
call.enqueue(new Callback<List<SpaceNews>>() {
@Override
public void onResponse(Call<List<SpaceNews>> call, Response<List<SpaceNews>> response) {
Log.d("gotApiData","got it");
}
@Override
public void onFailure(Call<List<SpaceNews>> call, Throwable t) {
Log.d("gotError","not got it");
t.printStackTrace();
}
});
我怎样才能让这个工作, 我会很感激任何建议!
【问题讨论】:
标签: java android api android-studio retrofit2