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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35841118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 00:39:20  来源:igfitidea点击:

How to get error message description using Volley

javaandroidandroid-volley

提问by GraphiteEdge

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.

我正在使用 Volley 库从 Android Java 向 ac# 后端发送 http 请求。后端应用程序以预期的错误代码和描述以及 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
                            }
                        }
                    );

This is the C# code processing the request:

这是处理请求的 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");

[WebInvoke(Method = "POST", UriTemplate = "users", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] [OperationContract] void addUser(String username, String firstname, String lastname, String电子邮件,字符串哈希){ Console.WriteLine(DateTime.Now +“收到的数据包”);

        //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;
    }

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.

我已经浏览了其他人的问题,但似乎无法找到我正在寻找的答案。有人知道怎么做吗?我尝试过的许多方法都导致空花括号,表示 JSON 的主体为空。我正在专门尝试获取状态描述。

回答by Ivan Ivanov

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

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

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

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

回答by Uncaught Exception

The data field of networkResponse is a JSON string of the form:

networkResponse 的数据字段是以下形式的 JSON 字符串:

{"response":false,"msg":"Old Password is not correct."}

{"response":false,"msg":"旧密码不正确。"}

So you need to get the value corresponding to "msg" field, like this (ofcourse with all exception catching):

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

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

Tested with Volley 1.1.1

使用 Volley 1.1.1 测试

回答by Robert Banyai

you have to override parseNetworkError and deliverError methods and you can get errormessage from them.

你必须覆盖 parseNetworkError 和 deliveryError 方法,你可以从他们那里得到错误消息。

回答by Robert Banyai

Example to override methods :

覆盖方法的示例:

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 + ")");
        }
    }){
        @Override
        protected VolleyError parseNetworkError(VolleyError volleyError) {
            return super.parseNetworkError(volleyError);
        }

        @Override
        public void deliverError(VolleyError error) {
            super.deliverError(error);
        }
    };

回答by BNK

IMO, you should override parseNetworkErroras below:

IMO,您应该覆盖parseNetworkError如下:

@Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
    String json;
    if (volleyError.networkResponse != null && volleyError.networkResponse.data != null) {
        try {
            json = new String(volleyError.networkResponse.data,
                    HttpHeaderParser.parseCharset(volleyError.networkResponse.headers));
        } catch (UnsupportedEncodingException e) {
            return new VolleyError(e.getMessage());
        }
        return new VolleyError(json);
    }
    return volleyError;
}

Then, inside onErrorResponse(VolleyError error), you can use Log.e(LOG_TAG, error.toString());for example. Hope it helps!

然后,在里面onErrorResponse(VolleyError error),您可以使用Log.e(LOG_TAG, error.toString());例如。希望能帮助到你!

回答by Diako Hasani

for get type error you can use this code

对于获取类型错误,您可以使用此代码

JsonArrayRequest request=new JsonArrayRequest(Request.Method.POST,Url,input,response ->{}  ,error -> {

 if (error instanceof TimeoutError) {
      //For example your timeout is 3 seconds but the operation takes longer
 }

 else if (error instanceof ServerError) {
        //error in server
 }

 else if (error instanceof NetworkError) {
        //network is disconnect
 }

 else if (error instanceof ParseError) {
        //for cant convert data
 }

 else {
        //other error
 }
 });

for get error message you can use this code

要获取错误消息,您可以使用此代码

String Message=error.toString();