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

相关内容

热门资讯

教学盘点!xpoker辅助怎么... 教学盘点!xpoker辅助怎么用(辅助挂)竟然存在有挂(有挂分析)1、xpoker辅助怎么用透视辅助...
攻略讲解!智星德州辅助译码插件... 攻略讲解!智星德州辅助译码插件靠谱吗(辅助挂)果然真的有挂(有挂解密)1、用户打开应用后不用登录就可...
实测发现!wepoker辅助器... 实测发现!wepoker辅助器激活码(辅助挂)其实有挂(真的有挂)该软件可以轻松地帮助玩家将wepo...
一分钟揭秘!德州局透视脚本免费... 一分钟揭秘!德州局透视脚本免费版下载手机版(辅助挂)切实是有挂(有挂工具)小薇(辅助器软件下载)致您...
我来教大家!wepoker底牌... 我来教大家!wepoker底牌透视(辅助挂)竟然存在有挂(竟然有挂)1、不需要AI权限,帮助你快速的...
记者爆料!wepoker作弊方... 记者爆料!wepoker作弊方法(辅助挂)总是是有挂(有挂技术)1、点击下载安装,wepoker作弊...
分享个大家!epoker透视(... 分享个大家!epoker透视(辅助挂)真是存在有挂(有挂技巧)epoker透视能透视中分为三种模型:...
总算明白!wepoker看底牌... 总算明白!wepoker看底牌(辅助挂)一贯真的有挂(有挂方略)1、进入游戏-大厅左侧-新手福利-激...
揭秘!wepoker私人局俱乐... 揭秘!wepoker私人局俱乐部(辅助挂)真是有挂(有挂方法)该软件可以轻松地帮助玩家将wepoke...
玩家必备科技!wepoker提... 玩家必备科技!wepoker提高好牌率(辅助挂)一贯真的有挂(详细教程)1、该软件可以轻松地帮助玩家...