You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Retrofit提交raw格式Body请求失败、response.body为空如何解决?

Retrofit提交Raw JSON常见问题解决方案

一、初始提交数据失败、response.body为空问题解决

  • 检查BASE_URL格式是否正确:必须以/结尾,否则会导致请求路径拼接错误
  • 检查@POST注解的路径配置:如果你的BASE_URL已经包含子路径(比如https://example.com/api/v1/),@POST("/")会强制请求根路径https://example.com/,覆盖原有子路径,需要根据实际接口调整路径值
  • 检查数据模型字段匹配:你当前DataItem类中longtitude拼写错误(正确经度字段名为longitude),如果后端使用标准拼写接收参数,会导致参数丢失,可以添加Gson序列化注解修正:
// DataItem类中修正字段映射
@SerializedName("longitude")
private String longtitude;

也可以直接修改字段名为正确拼写避免问题

  • 显式指定请求头:确保请求Content-Type符合后端要求,在请求接口添加注解:
public interface SendData {
    @Headers("Content-Type: application/json")
    @POST("你的实际接口路径")
    Call<DataItem> sendData(@Body DataItem body);
}
  • 添加日志拦截器排查请求参数:引入OkHttp日志拦截器打印完整请求报文,确认提交的JSON是否符合预期:
public class ApiClient {
    public static Retrofit retrofit;
    private static final String BASE_URL = BuildConfig.BASE_URL;

    public static Retrofit getRetrofitInstance(){
        // 配置日志拦截器
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .build();

        if (retrofit == null){
            retrofit =  new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return  retrofit;
    }
}
  • 增加响应状态判断:原代码没有判断请求是否成功,接口返回4xx/5xx错误码时也会走onResponse但body为空,需要先判断response.isSuccessful():
@Override
public void onResponse(Call<DataItem> call, Response<DataItem> response) {
    if (response.isSuccessful()) {
        // 请求成功逻辑
        String result = String.valueOf(response.body());
        Log.d("MainActivity", "result = " + result);
    } else {
        // 请求失败逻辑,打印错误信息
        Log.d("MainActivity", "错误码:" + response.code() + " 错误内容:" + response.errorBody().string());
    }
    timingSendData();
}

二、数据提交成功但回调走onFailure问题解决

该问题绝大多数是响应体解析失败导致,可按以下步骤排查:

  • 确认接口返回结构:如果后端提交成功后返回的结构和DataItem不匹配、返回空响应、返回纯文本而非JSON,Gson解析会抛出异常触发onFailure,可以先将接口返回泛型改为ResponseBody拿到原始响应确认结构:
public interface SendData {
    @Headers("Content-Type: application/json")
    @POST("你的实际接口路径")
    Call<ResponseBody> sendData(@Body DataItem body);
}
  • 如果接口提交成功后返回空响应(204 No Content),直接将泛型改为Void即可避免解析失败:
public interface SendData {
    @Headers("Content-Type: application/json")
    @POST("你的实际接口路径")
    Call<Void> sendData(@Body DataItem body);
}
  • 检查网络配置:确认AndroidManifest已添加网络权限,若使用http明文地址,Android 9及以上系统默认禁止明文传输,需要添加网络安全配置放开限制。

内容的提问来源于stack exchange,提问作者Thoriqul Umar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 10:54:01