【问题标题】:Volley error output the error message sent from server sideVolley error 输出服务器端发送的错误信息
【发布时间】:2019-09-25 07:10:37
【问题描述】:

我在 php 中使用 volley 并返回错误,其结构如下,如 postman 所示

{
  "name": "Exception",
  "message": "Unable to verify your accont",
  "code": 500,
  "type": "yii\\base\\UserException"
}

现在我想阅读上面的错误消息,所以在我的排球字符串请求中我有

    StringRequest stringRequest = new StringRequest(this.request_method, this.api_url,
            response -> {

             },
            error -> {
            //here process the error
            if (error instanceof ServerError || error instanceof AuthFailureError){
             NetworkResponse response = er.networkResponse;
             switch (response.statusCode){
              case 500:{
               HashMap<String, String> result = new Gson().fromJson(....); //stuck

               }
             }
            }) {
        @Override
        public String getBodyContentType() {
            return "application/json; charset=utf-8";
        }         
    };

我坚持如何从凌空错误中读取错误消息。我如何在有或没有 gson 的情况下进行

我仍然想使用字符串请求,因为我希望我的 php 响应是一个 json 编码的字符串。

【问题讨论】:

    标签: android android-volley


    【解决方案1】:

    尝试这种方式来读取来自NetworkResponse的响应

    对于科特林

    val response = er.networkResponse
    val jsonError = String(response.data)
    val responseObject = JSONObject(response)
    val message = responseObject.optString("message")
    

    对于java

    NetworkResponse response = er.networkResponse;
    String responseData = new String(response.data,"UTF-8");
    JSONObject responseObject =new  JSONObject(response)
    String message = responseObject.optString("message")
    

    【讨论】:

      【解决方案2】:

      使用

      String errorResponse = new String(error.networkResponse.data);
      

      然后将此字符串转换为您的 json 对象

      【讨论】:

        【解决方案3】:

        尝试从您的 api 响应中获取 response.errorbody

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-04-03
          • 1970-01-01
          • 2014-05-12
          • 2023-03-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多