Retrofit请求返回NULL响应,请求排查代码问题
Retrofit调用API时response.body()始终为NULL的排查方案
我在使用Retrofit调用API获取设备数据时,响应体(response.body())始终为NULL,无法获取有效数据。以下是相关代码,请帮忙排查:
DeviceFetcher.java
public class DeviceFetcher extends AppCompatActivity { private static final String BASE_URL = "https://base-url/"; public static void fetchDevices() { Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); String token = SplashScreen.getTOKEN(); ApiService apiService = retrofit.create(ApiService.class); Call<DeviceResponse> call = apiService.getDevices("jwt" + token); call.enqueue(new Callback<DeviceResponse>() { @Override public void onResponse(Call<DeviceResponse> call, Response<DeviceResponse> response) { Log.e("DEVICEFETCHER", "Response: " + response.body()); if (response.isSuccessful()) { DeviceResponse responseData = response.body(); if (responseData != null) { } } else { System.out.println("NO RESPONSE = NULL"); // Handle API error } } @Override public void onFailure(Call<DeviceResponse> call, Throwable t) { Log.e("DEVICEFETCHER", "Error: " + t.getLocalizedMessage()); } }); } }
ApiService.java
public interface ApiService { String BASE_URL = "https://base-url/"; String accessToken = SplashScreen.getTOKEN(); @GET("devices") Call<DeviceResponse> getDevices(@Header("Authorization") String authHeader); }
排查要点
- 检查Authorization头格式:当前传的是
"jwt" + token,多数JWT接口要求的格式是Bearer <token>,确认API文档要求的认证头格式,若不符会导致API返回非2xx状态码,response.body()为空。 - 打印完整响应日志:在
onResponse中补充以下日志,明确API返回的状态码、错误信息和原始响应内容,排查是状态码问题还是Gson解析失败:Log.e("DEVICEFETCHER", "Response code: " + response.code()); Log.e("DEVICEFETCHER", "Response message: " + response.message()); // 打印错误响应的原始内容 if (!response.isSuccessful() && response.errorBody() != null) { try { Log.e("DEVICEFETCHER", "Raw error response: " + response.errorBody().string()); } catch (IOException e) { e.printStackTrace(); } } - 校验DeviceResponse实体类:确保实体类的字段名、数据类型、嵌套结构和API返回的JSON完全匹配(包括大小写、是否有SerializedName注解适配字段名)。Gson解析不匹配时不会抛出异常,直接返回null。
- 修正Activity静态方法的不合理写法:DeviceFetcher继承了AppCompatActivity,但
fetchDevices是静态方法,这种设计容易引发上下文相关问题。建议将Retrofit实例封装为单例,脱离Activity依赖。 - 确认BASE_URL和Token有效性:检查BASE_URL是否正确(必须以
/结尾),以及SplashScreen.getTOKEN()获取的token是否未过期、格式正确。可以用Postman直接携带该token调用API,验证接口本身是否正常。
内容的提问来源于stack exchange,提问作者Amorphous
相关产品推荐
相关产品推荐

