【问题标题】:Retrofit is not making api call改造没有进行 api 调用
【发布时间】:2018-05-25 14:31:20
【问题描述】:

我正在使用改造 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 中设置了 Internet 权限。

【问题讨论】:

  • “卡住”是什么意思?碰撞?还是?
  • 不,它没有崩溃,只是进程没有继续,我在logcat中看不到任何警告或错误
  • @aloj 你的问题解决了吗?我面临着类似的问题

标签: android retrofit retrofit2


【解决方案1】:

你可以尝试使用Retrofit2 和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 类,但您可以使用 json 响应创建代码 http://www.jsonschema2pojo.org/服务

【讨论】:

  • RxJava 在某些情况下可能确实很方便,但我看不出添加 RxJava 支持将如何解决 OP 的问题。
【解决方案2】:

我认为您执行错误的onResponse() 或Callback(),因为我也在使用Retrofit 2,其中onResponse() 看起来像这样:

@Override
public void onResponse(Response<ListJsonResponseRestaurant> response, Retrofit retrofit) {
    ...
    ...
}

【讨论】:

    猜你喜欢
    • 2017-01-11
    • 2016-12-31
    • 2019-01-17
    • 2018-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 2018-02-01
    相关资源
    最近更新 更多