android - 改造 response.errorBody() 为空

标签 android json retrofit okhttp

我正在执行一些 REST 调用,并得到响应。有时,响应不会正常,所以我需要解析响应,并以适当的方式呈现给用户注意和 react 。我有这段代码:

if(response.code()!=200){
      JSONArray jsonError=null;
      try {
         Log.i("David", "Incorrect response: "+response.errorBody().string());

         jsonError = new JSONArray(response.errorBody().string());//After this line, jsonError is null
         JSONObject message=jsonError.getJSONObject(0);

         String errorJson=message.getString("message");
         Log.i("David", "Error received: "+errorJson);
         AlertDialog.Builder dialog=new AlertDialog.Builder(getActivity());
         dialog.setTitle(getString(R.string.error));
         dialog.setMessage(getString(R.string.errorfound) + errorJson);
         dialog.setPositiveButton(getString(R.string.aceptar), new DialogInterface.OnClickListener() {
             @Override
             public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
              }
                  });
                            dialog.show();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

这样,日志行“Incorrect response”完美显示,包含错误代码、消息等。这是收到的 JSON:

[{"coderror":"-2","gravedad":"1","message":"Device imei 34543564768463435345 not logged in","cause":""}]

我的问题是,正如我所说,日志记录工作正常,但是当我尝试将 JSON 转换为 JsonArray 时...它失败了。在下一行中,JsonError 对象结果为 null。

为什么我无法解析响应?谢谢。

最佳答案

正如我所说,您应该使用 String s = response.errorBody().string(); 然后 Log.i("David", "Incorrect response: "+ s ;jsonError = new JSONArray(s);。不要调用 response.errorBody().string() 两次。

如果您尝试/捕获 IllegalStateExceptionException,您将在 logcat 中获得如下所示的信息

W/System.err: java.lang.IllegalStateException: closed
W/System.err:     at com.squareup.okhttp.internal.http.HttpConnection$FixedLengthSource.read(HttpConnection.java:415)
W/System.err:     at okio.Buffer.writeAll(Buffer.java:956)
W/System.err:     at okio.RealBufferedSource.readByteArray(RealBufferedSource.java:92)
W/System.err:     at com.squareup.okhttp.ResponseBody.bytes(ResponseBody.java:57)
W/System.err:     at com.squareup.okhttp.ResponseBody.string(ResponseBody.java:83)

希望对您有所帮助!

关于android - 改造 response.errorBody() 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33646197/

相关文章:

android.support.v7.widget.AppCompatTextView 无法转换为 android.widget.ImageView

android - PreferenceActivity 中的 createViewFromResource 出现 NullPointerException

android - 如何制作 apollo graphql 客户端自动生成的类,Parcelable

java - JSON解析数组和同名单个对象

javascript - JSON 返回未定义

kotlin - 基于 bool 值的Rx Java调用Api

android - Alexa App 不遵循 ASP.NET Core Identity 发出的 302 重定向

python - Python 或 Django 中的 CURL

java - Android Retrofit API 使用

java - 使用 Retrofit 和填充 RecyclerView 的 JSON ArrayList 问题