Java 使用 Volley 获取成功请求的 HTTP 状态代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26015610/
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-08-11 01:41:57  来源:igfitidea点击:

Get HTTP status code for successful requests with Volley

javaandroidandroid-volley

提问by Addev

I'm retrieving the content of a invalid web address with volley, i.e. http://www.gigd32fdsu.com: This is my test code:

我正在使用 volley 检索无效网址的内容,即http://www.gigd32fdsu.com:这是我的测试代码:

// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
final String url = "http://www.gigd32fdsu.com";

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, 
new Response.Listener() {
    @Override
    public void onResponse(Object response) {
        // Display the first 500 characters of the response string.
        mTextView.setText("Response is: " + response.toString().substring(0, 500));
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        mTextView.setText("That didn't work! " + error.networkResponse.statusCode);
    }
});
// Add the request to the RequestQueue.
queue.add(stringRequest);

When I run this code I receive the callback onResponse(String) with an error page from my ISP. How can I read the HTTP status code in order to detect that the web displaying is not correct?

当我运行此代码时,我从我的 ISP 收到带有错误页面的回调 onResponse(String)。如何读取 HTTP 状态代码以检测 Web 显示不正确?

Thanks

谢谢

回答by VinceStyling

Just override the parseNetworkResponsemethod then take the statusCodevalue.

只需覆盖parseNetworkResponse方法然后statusCode取值。

public class StrImplRequest extends StringRequest {
    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response) {
        // take the statusCode here.
        response.statusCode;
        return super.parseNetworkResponse(response);
    }
}

回答by Dantalian

I will make the response from VinceStyling more complete. I'll tell you what I do.

我会让 VinceStyling 的回复更加完整。我会告诉你我在做什么。

Once you override this method, save the statusCode in your class.

覆盖此方法后,将 statusCode 保存在您的类中。

        @Override
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            statusCode=response.statusCode;
            return super.parseNetworkResponse(response);
        }

After that you should compare it with HttpURLConnection constants to act accordingly. For example:

之后,您应该将其与 HttpURLConnection 常量进行比较以采取相应的行动。例如:

            int statusCode=webService.getStatusCode();
            switch (statusCode){
                case HttpURLConnection.HTTP_OK:
                    //do stuff
                    break;
                case HttpURLConnection.HTTP_NOT_FOUND:
                    //do stuff
                    break;
                case HttpURLConnection.HTTP_INTERNAL_ERROR:
                    //do stuff
                    break;
            }

回答by 5er

Simple solution is to override parseNetworkResponse in makeStringReq(), no need for another class:

简单的解决方案是在 makeStringReq() 中覆盖 parseNetworkResponse,不需要另一个类:

private void makeStringReq() {
    showProgressDialog();

    StringRequest strReq = new StringRequest(Method.GET,
            Const.URL_STRING_REQ,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.d(TAG, response.toString());
                    msgResponse.setText(response.toString());
                    hideProgressDialog();

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                    hideProgressDialog();
                }
            }) {

        @Override
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            int mStatusCode = response.statusCode;
            return super.parseNetworkResponse(response);
        }
    };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);

}

回答by Chauyan

@VinceStyling 's answer is ok, or you can extend Request class and do what you wanna do. For example,

@VinceStyling 的回答是可以的,或者您可以扩展 Request 类并做您想做的事情。例如,

    ServerStatusRequestObject extends Request {

    private final Response.Listener mListener;
    private String mBody = "";
    private String mContentType;

    public ServerStatusRequestObject(int method,
                                     String url,
                                     Response.Listener listener,
                                     Response.ErrorListener errorListener) {

        super(method, url, errorListener);
        mListener = listener;
        mContentType = "application/json";

        if (method == Method.POST) {
            RetryPolicy policy = new DefaultRetryPolicy(5000, 0, 5);
            setRetryPolicy(policy);
        }
    }

    @Override
    protected Response parseNetworkResponse(NetworkResponse response) {
        return Response.success(response.statusCode, HttpHeaderParser.parseCacheHeaders(response));
    }

    @Override
    protected void deliverResponse(Object response) {
        if (mListener != null) {
            mListener.onResponse(response);
        }
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        return mBody.getBytes();
    }

    @Override
    public String getBodyContentType() {
        return mContentType;
    }

    @Override
    public int compareTo(Object another) {
        return 0;
    }

then in your response handler, you can still receive the whole messages from server. Try it.

然后在您的响应处理程序中,您仍然可以从服务器接收整个消息。尝试一下。