如何使用Volley获取错误消息说明 [英] How to get error message description using Volley

查看:126
本文介绍了如何使用Volley获取错误消息说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Volley库将来自Android Java的http请求发送到c#后端.后端应用程序以预期的错误代码和描述以及StatusDescription进行响应.我可以通过Wireshark查看响应状态描述,但不知道如何在android端获取描述字符串.

I'm sending an http request from Android Java using the Volley library to a c# backend. The backend application responds with a error code and description as intended, as well as a StatusDescription. I can see the response status description through wireshark but do not know how to get the description string on the android side.

    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#代码:

This is the C# code processing the request:

[WebInvoke(方法="POST",UriTemplate =用户",BodyStyle = WebMessageBodyStyle.Wrapped,RequestFormat = WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json)] [运营合同] void addUser(字符串用户名,字符串姓氏,字符串姓氏,字符串电子邮件,字符串哈希) { Console.WriteLine(DateTime.Now +收到数据包");

[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的内容为空.我正在专门尝试获取状态说明.

I've looked through other peoples questions but can't seem to find the answer I'm looking for. Anyone know how to do this? Many methods I have tried resulted in empty curly braces, indicating JSON with an empty body. I am trying specifically to get the status description.

推荐答案

尝试使用此自定义方法:

Try with this custom method:

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) {
        }
    }

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

It will show toast with error message from the request. Call this in onErrorResponse method in your volley request:

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

这篇关于如何使用Volley获取错误消息说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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