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

如何在Retrofit请求体中以Raw JSON形式POST JSONObject

解决Retrofit POST请求体为空、400 Bad Request问题

问题根源

直接用String作为@Body参数时,Retrofit可能无法正确将其识别为JSON格式的请求体,导致服务器接收不到有效数据,返回400错误。Postman能正常工作是因为你手动指定了请求体为raw JSON,而Android端的Retrofit配置没匹配上。

修复方案

方案一:直接传递JSONObject作为@Body参数

修改Retrofit接口,把参数类型从String改成JSONObject:

@POST("Sync_Status")
@Headers("Content-Type: application/json; charset=utf-8")
Call<String> LookupSyncStatus(@Body JSONObject json, @Header("Authorization") String authToken);

调用时直接传入JSONObject,无需转成String:

public void SyncStatus(JSONObject requestbody, RetrofitCallback<String> retrofitCallback){
    Call<String> call = RetrofitClientInterface.getUserService().LookupSyncStatus(requestbody, authkey);
    callForStatusJson(call, retrofitCallback);
}

方案二:用RequestBody包装String类型的JSON

如果必须用String传递,就把String包装成RequestBody,明确指定媒体类型:
修改接口:

@POST("Sync_Status")
Call<String> LookupSyncStatus(@Body RequestBody json, @Header("Authorization") String authToken);

调用时转换String为RequestBody:

public void SyncStatus(String requestbody, RetrofitCallback<String> retrofitCallback){
    RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestbody);
    Call<String> call = RetrofitClientInterface.getUserService().LookupSyncStatus(body, authkey);
    callForStatusJson(call, retrofitCallback);
}

额外检查

确保你的Retrofit初始化代码添加了GsonConverterFactory,否则无法正确序列化JSON:

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .client(okHttpClient)
    .build();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 12:25:02