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

2022-09-01 18:51:23

我正在用凌空抽射检索无效网址的内容,即:这是我的测试代码: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);

当我运行此代码时,我收到来自ISP的Response(String)上的回调,其中包含错误页面。如何读取 HTTP 状态代码以检测网页显示不正确?

谢谢


答案 1

简单的解决方案是在 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);

}

答案 2

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

重写此方法后,将 statusCode 保存在类中。

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

之后,您应该将其与 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;
            }

推荐