Android 改造 GET 调用响应为 NULL

Android Retrofit GET call response is NULL

嗨,我 google 这个问题已经持续 8 到 9 个小时了。实际上我无法找到我在这里做的错误是什么。

我有两个网络电话。一是登录。它工作正常。我正在使用 Retrofit。

但是我有另一个网络电话。它没有按预期工作。我通过我的代码得到的响应为 null 是我在 chrome 中执行调用,我得到了响应。很好,下面是我的代码。请帮助我哪里做错了。

建设gradle

//retrofit for networkcall
implementation 'com.squareup.retrofit2:retrofit:2.1.0'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.0.0-RC1'
implementation 'com.google.code.gson:gson:2.8.6'

ApiClient.java

public class ApiClient {
    private static final String BASE_URL = Constants.BASE_URL;
    private static Retrofit retrofit = null;


    public static Retrofit getClient() {
        //OkHttpClient client = new OkHttpClient();
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();
        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();
        }
        return retrofit;
    }

}

ApiInterface.java

public interface ApiInterface {
    @FormUrlEncoded
    @POST(Constants.TOKEN_URL)
    Call<Token> getToken(@Field("username") String username, @Field("password") String password, @Field("grant_type") String grant_type);

    @GET(Constants.GET_VEHICLE_BRAND_COUN_TLIST_URL) // here is method i am trying to call in my activity class.
    Call<JSONArray> getVehicleBrandCountList();
}

MainActivity.java

private void getLoggedInUserData( String bearerToken) {
    ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
    Call<JSONArray> call = apiService.getVehicleBrandCountList();
    call.enqueue(new Callback<JSONArray>() {
        @Override
        public void onResponse(Call<JSONArray> call, Response<JSONArray> response) {
            try{
                Log.e("body---",response.body().toString());
            }catch(Exception e) {
                e.printStackTrace();
            }
        }
        @Override
        public void onFailure(Call<JSONArray> call, Throwable t) {
            Log.e(this + "-----", t.toString());
        }
    });
}

我用浏览器测试了图像中的端点,它似乎发回了 XML 响应而不是 JSON。但是从 Postman(测试 API 调用的软件)看来它可以向您发送 JSON 格式的响应。

尝试在您的 GET 调用中添加 "Accept" header,以指明您希望接收响应的格式。

 @Headers({"Accept: application/json"})
 @GET(Constants.GET_VEHICLE_BRAND_COUN_TLIST_URL) // here is method i am trying to call in my activity class.
    Call<JSONArray> getVehicleBrandCountList();
}