如何使用 Volley 获取错误消息说明

2022-09-03 03:40:45

我正在使用Volley库从Android Java向c#后端发送http请求。后端应用程序按预期使用错误代码和描述以及状态描述进行响应。我可以通过wireshark看到响应状态描述,但不知道如何在Android端获取描述字符串。

    final JsonObjectRequest request = new JsonObjectRequest(JsonObjectRequest.Method.POST,
                                url,json,
                            new Response.Listener<JSONObject>() {

                                @Override
                                public void onResponse(JSONObject response) {
                                    TextView mTextView = (TextView) findViewById(R.id.output);
                                    print("Success");
                                }
                            }, new Response.ErrorListener() {

                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    TextView mTextView = (TextView) findViewById(R.id.output);
                                    print("Failure (" + error.networkResponse.statusCode + ")");
//Trying to get the error description/response phrase here
                            }
                        }
                    );

这是处理请求的 C# 代码:

[WebInvoke(Method = “POST”, UriTemplate = “users”, BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)][OperationContract] void addUser(String username, String firstname, String lastname, String email, String hash) { Console.WriteLine(DateTime.Now + “ Packet receieved”);

        //Stores the response object that will be sent back to the android client
        OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
        String description = "User added";
        response.StatusCode = System.Net.HttpStatusCode.OK;

        //Tries to add the new user
        try
        {
            userTable.Insert(username,firstname,lastname,email,hash);
        }
        catch (SqlException e)
        {
            //Default response is a conflict
            response.StatusCode = System.Net.HttpStatusCode.Conflict;

            description = "Bad Request (" + e.Message + ")";

            //Check what the conflict is
            if (userTable.GetData().AsEnumerable().Any(row => username == row.Field<String>("username")))
            {
                description = "Username in use";
            }
            else if (userTable.GetData().AsEnumerable().Any(row => email == row.Field<String>("email")))
            {
                description = "Email address in use";
            }
            else
            {
                response.StatusCode = System.Net.HttpStatusCode.BadRequest;
            }
        }

        //display and respond with the description
        Console.WriteLine(description);
        response.StatusDescription = description;
    }

我浏览了其他人的问题,但似乎找不到我正在寻找的答案。有人知道如何做到这一点吗?我尝试过的许多方法都会导致空的大括号,表示带有空正文的 JSON。我正在专门尝试获取状态描述。


答案 1

请尝试使用以下自定义方法:

public void parseVolleyError(VolleyError error) {
        try {
            String responseBody = new String(error.networkResponse.data, "utf-8");
            JSONObject data = new JSONObject(responseBody);
            JSONArray errors = data.getJSONArray("errors");
            JSONObject jsonMessage = errors.getJSONObject(0);
            String message = jsonMessage.getString("message");
            Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
        } catch (JSONException e) {
        } catch (UnsupportedEncodingException errorr) {
        }
    }

它将显示来自请求的包含错误消息的 Toast。在凌空请求中调用 onErrorResponse 方法:

new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                           parseVolleyError(error);
                        }
                    }

答案 2

networkResponse 的数据字段是一个 JSON 字符串,其形式为:

{“response”:false,“msg”:“旧密码不正确。

因此,您需要获取与“msg”字段相对应的值,如下所示(当然,所有异常捕获):

String responseBody = new String(error.networkResponse.data, "utf-8");
JSONObject data = new JSONObject(responseBody);
String message = data.optString("msg");

使用凌空 1.1.1 进行测试


推荐