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的问题,并能够获取到错误消息。

相关内容

热门资讯

透视游戏"wepok... 透视游戏"wepoker有辅助功能吗"详细辅助AA德州教程(透视脚本神器);科技安装教程;13670...
透视新版"pokem... 透视新版"pokemmo手机脚本辅助器"详细辅助透牌教程(购买模拟器软件)是一款可以让一直输的玩家,...
透视规律"hhpok... 透视规律"hhpoker有没有作弊辅助"详细辅助教你攻略(私局代打软件);科技安装教程;136704...
透视脚本"hhpok... 透视脚本"hhpoker万能辅助器"详细辅助透明教程(破解工具辅助)1、玩家可以在hhpoker万能...
透视科技"德州局透视... 您好,德州局透视这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家在这款游...
透视攻略"hhpok... 透视攻略"hhpoker怎么防作弊"详细辅助专业教程(辅助器免费辅助);亲真的是有正版授权,小编(透...
透视游戏"福建大菠萝... 此外,数据分析德州(福建大菠萝万能辅助器)辅助神器app还具备辅助透视行为开挂功能,通过对客户福建大...
透视ai代打"智星德... 透视ai代打"智星德州辅助译码插件靠谱吗"详细辅助必备教程(-h5下载方法);支持多人共享记分板与复...
透视辅助"佛手在线大... 透视辅助"佛手在线大菠萝辅助"详细辅助新2025版(的辅助器方法)1、很好的工具软件,可以解锁游戏的...
透视私人局"wepo... 透视私人局"wepokerplus作弊"详细辅助必赢方法(底牌透视透明);人气非常高,ai更新快且高...