在Retrofit2中接收响应主体但是onResponse没有被调用

时间:2016-05-16 13:50:18

标签: android json retrofit2

我从API调用中收到一个正文,但onResponse()没有被调用,以下是方法:

final Rest_manager_league rest = new Rest_manager_league();
Call<List<Root>> listCall = rest.getMLeague_conn().getLeague(x);
listCall.enqueue(new Callback<List<Root>>() {
    @Override
    public void onResponse(Call<List<Root>> call, Response<List<Root>> response) {
        lg = response.body();
        Log.d("res", "ON");
        if (response.isSuccessful()){
            textView.setText(lg.get(3).getStanding().get(2).getTeamName());
            Log.d("s", "true");
        }
    }

    @Override
    public void onFailure(Call<List<Root>> call, Throwable t) {
        Log.d("Failure", "Failed");
    }
});

这是Retrofit界面&amp;服务:

public interface league_Conn {
    @GET("/v1/soccerseasons/{id}/leagueTable")
    @Headers("X-Auth-Token:" +
            "1869f69f772b40a2a12fd6eefb4e48ef ")
    Call<List<Root>> getLeague(@Path("id") int id);
}

public class Rest_manager_league {
    private league_Conn mleague_conn;

    public league_Conn getMLeague_conn() {

        if (mleague_conn == null) {

            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            OkHttpClient client = new OkHttpClient.Builder().addInterceptor(logging).build();
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("http://api.football-data.org/")
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(client)
                    .build();
            mleague_conn = retrofit.create(league_Conn.class);

        }


        return mleague_conn;
    }
}

在logcat中,onFailure()正在显示。像这样:

okhttp3 <-- END HTTP (8300 byte body) Failer :Failed

为什么onResponse()没有被调用?

1 个答案:

答案 0 :(得分:4)

您正在获取响应正文(8300字节),但onFailure正在调用,因为您返回的正文与您的GSONFactory不一致。反序列化过程不起作用。您可以通过打印@yazan指出的堆栈跟踪来查明问题。只需输入:

t.printStackTrace()
onFailure()中的

修改

发生错误是因为您告诉Retrofit您期望列表,而不是您正在获取JSON对象。我快速浏览了您正在使用的API,它看起来像是返回一个JSON对象,然后返回的对象包含您有兴趣访问的列表。尝试将List<Root>的实例替换为Root。如需更多帮助,您还可以查看以下问题:

GSON throws Expected BEGIN_ARRAY but was BEGIN_OBJECT error