Retrofit 2.0-如何获取400 Bad Request错误的响应正文? [英] Retrofit 2.0 - How to get response body for 400 Bad Request error?

查看:73
本文介绍了Retrofit 2.0-如何获取400 Bad Request错误的响应正文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,当我对服务器进行POST API调用时,我会收到一个JSON响应为400 Bad Request的错误.

So when I make a POST API call to my server, I get a 400 Bad Request error with JSON response.

{
    "userMessage": "Blah",
    "internalMessage": "Bad Request blah blah",
    "errorCode": 1
}

我叫

Call.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        //AA
    }

    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
        //BB
    }
}

但是问题是,一旦我得到响应,就会调用onFailure()以便调用//BB.在这里,我无法访问JSON响应.当我记录api请求和响应时,它根本不显示JSON响应.Throwable t是IOException.但是,奇怪的是,当我在Postman上进行相同的调用时,它确实返回了带有400错误代码的预期JSON响应.

However the problem is that once I get the response, onFailure() is invoke so that //BB is called. Here, I have no way to access the JSON response. When I log the api request and response, it doesn't show JSON response at all. And Throwable t is IOException. However, strangely, when I make the same call on Postman, it does return the expected JSON response with 400 error code.

所以我的问题是,当我收到400 Bad Request错误时如何获得json响应?我应该添加一些东西到okhttpclient吗?

So my question is how can I get the json response when I get 400 Bad Request error? Should I add something to okhttpclient?

谢谢

推荐答案

您可以在 onResponse 方法中进行操作,请记住 400 是响应状态,不是错误:

You can do it in your onResponse method, remember 400 is a response status not an error:

if (response.code() == 400) {              
    Log.v("Error code 400",response.errorBody().string());
}

您可以使用 Gson 来处理除200-300 之外的任何响应代码,如下所示:

And you can handle any response code except 200-300 with Gson like that:

if (response.code() == 400) {
   Gson gson = new GsonBuilder().create();
   ErrorPojoClass mError=new ErrorPojoClass();
   try {
       mError= gson.fromJson(response.errorBody().string(),ErrorPojoClass.class);
       Toast.makeText(context, mError.getDescription(), Toast.LENGTH_LONG).show();
   } catch (IOException e) {
       // handle failure to read error
   }        
}

将此添加到您的 build.gradle 中:编译'com.google.code.gson:gson:2.7'

如果要创建 Pojo 类,请转到 Json Schema 2 Pojo 并粘贴您的示例 Json 响应.选择源类型 Json 和注释 Gson .

If you want create Pojo class go to Json Schema 2 Pojo and paste your example Json response. Select source type Json and annotation Gson .

这篇关于Retrofit 2.0-如何获取400 Bad Request错误的响应正文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆