我正在使用改造2向我的服务器进行api调用,但在尝试进行api调用时它被卡住了。这是我的代码
public interface GOTApi {
@GET("characters.json")
Call<GOTCharacterResponse> getCharacters();
}
中间类获取数据
public class GOTCharacterResponse {
List<GOTCharacter> characters;
}
我的班级打api电话
public class GOTService {
public static final String BASE_URL = "https://project-8424324399725905479.firebaseio.com/";
public static GOTApi getGOTApi(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit.create(GOTApi.class);
}
public static void getCharacters(){
getGOTApi().getCharacters().enqueue(new Callback<GOTCharacterResponse>() {
@Override
public void onResponse(Call<GOTCharacterResponse> call, Response<GOTCharacterResponse> response) {
if(response.isSuccessful()){
}
}
@Override
public void onFailure(Call<GOTCharacterResponse> call, Throwable t) {
int a = 0;
}
});
}
}
这些是我正在使用的库
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
compile 'com.squareup.okhttp3:okhttp:3.3.1'
它总是被困在getCharacters()方法中。当然,我在Mainfest中设置了互联网权限。
您可以尝试将Retrofit 2与RxJava一起使用,它更方便。
public Retrofit providedRetrofit(OkHttpClient okHttpClient){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
return retrofit;
}
你的API界面会看起来像
public interface Api {
@GET("api/service/schedule/{filial}")
Observable<Response<GOTCharacter>> getSchedule(@Path("some_param") String param);
}
您还需要解析来自JSON的响应。您没有提供GOTCharacter类,但是您可以使用http://www.jsonschema2pojo.org/服务从json响应创建代码
我认为您实现了错误的onResponse()
ORCallback()
,因为我也在使用Retrofit 2,其中onResponse()
如下所示:
@Override
public void onResponse(Response<ListJsonResponseRestaurant> response, Retrofit retrofit) {
...
...
}