Android Retrofit:response.errorBody 不为 null,但 response.errorBody.string() 返回 null。
创始人
2024-08-15 09:00:46
0

response.errorBody()不为空但response.errorBody().string()返回null时,可以尝试使用response.errorBody().source().buffer().clone().readUtf8()来获取错误消息。

下面是一个使用Retrofit的示例代码:

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class MainActivity {

    private Retrofit retrofit;

    public void makeApiCall() {
        // 创建Retrofit实例
        retrofit = new Retrofit.Builder()
                .baseUrl("https://api.example.com/")
                .build();

        // 创建API接口实例
        ApiService apiService = retrofit.create(ApiService.class);

        // 发起API请求
        Call call = apiService.getData();

        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                if (response.isSuccessful()) {
                    // 处理成功的响应
                } else {
                    // 处理错误的响应
                    try {
                        String errorBodyString = response.errorBody().source().buffer().clone().readUtf8();
                        // 使用错误消息进行处理
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                // 处理请求失败
            }
        });
    }
}

以上示例中,在处理错误响应时使用response.errorBody().source().buffer().clone().readUtf8()来获取错误消息。请注意,需要捕获IOException异常。

这种方法能够解决response.errorBody().string()返回null的问题,并能够获取到错误消息。

相关内容

热门资讯

揭秘一下!wepoker免费脚... 揭秘一下!wepoker免费脚本咨询,hhpoker是正品吗,德州教程(有挂技巧)1、许多玩家不知道...
透视讲解!wepoker私人局... 透视讲解!wepoker私人局俱乐部辅助(透视)原来真的是有挂(详细辅助揭秘攻略);1、很好的工具软...
终于清楚!hhpoker作弊码... 终于清楚!hhpoker作弊码怎么用,wepoker有辅助插件吗,我来教教你(有挂辅助);玩家必备必...
透视了解!wpk透视辅助(透视... 透视了解!wpk透视辅助(透视)一直有挂(详细辅助大神讲解);1、wpk透视辅助系统规律教程、wpk...
一分钟揭秘!wepoker免费... 一分钟揭秘!wepoker免费脚本咨询,hhpoker有作弊的吗,新2025版(有挂教程);玩家必备...
透视透视挂!hhpoker是内... 透视透视挂!hhpoker是内部控制吗(透视)切实有挂(详细辅助曝光教程)1、ai辅助优化,发牌逻辑...
今日焦点!wepoker透视脚... 今日焦点!wepoker透视脚本免费下载,wepoker脚本,微扑克教程(有挂辅助)1、很好的工具软...
透视插件!wepoker透视器... 透视插件!wepoker透视器免费(透视)果然是真的有挂(详细辅助技巧教程)1、让任何用户在无需we...
必备科技!哈糖大菠萝怎么开挂,... 必备科技!哈糖大菠萝怎么开挂,哈糖大菠萝怎么挂,辅助教程(有挂技巧);实战中需综合运用上述技巧,并根...
透视游戏!poker worl... 透视游戏!poker world辅助(透视)一直是真的有挂(详细辅助安装教程)一、软件透明挂的定义与...