如何使用Volley获取错误消息描述

Gra*_*dge 7 java android android-volley

我正在使用Volley库从Android Java发送一个http请求到ac#backend.后端应用程序响应错误代码和描述,以及StatusDescription.我可以通过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
                            }
                        }
                    );
Run Code Online (Sandbox Code Playgroud)

这是处理请求的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;
    }
Run Code Online (Sandbox Code Playgroud)

我查看了其他人的问题,但似乎无法找到我正在寻找的答案.有人知道怎么做吗?我尝试过的许多方法都会产生空的花括号,表示JSON的空体.我正在努力获取状态描述.

Iva*_*nov 12

尝试使用此自定义方法:

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) {
        }
    }
Run Code Online (Sandbox Code Playgroud)

它将显示来自请求的错误消息的吐司.在您的截击请求中的onErrorResponse方法中调用此方法:

new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                           parseVolleyError(error);
                        }
                    }
Run Code Online (Sandbox Code Playgroud)


Unc*_*ion 9

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");
Run Code Online (Sandbox Code Playgroud)

使用 Volley 1.1.1 测试