Getting headers from a response in volley

2019-01-20 08:02发布

I am working with Volley, I want to make request to a server which returns me a JSON in the "vissible layer" (I can see it in the web browser). My problem is that the server also returns my in the headers information that I need to get in my App, but I am not able to get the headers from the request.

I have searched a long time but I havent found anything usefull (Onlye adding data to the request Header, but not getting data from the header´s response)

Anyone knows how to implement that?

3条回答
时光不老,我们不散
2楼-- · 2019-01-20 08:12

If the request is returning json you should be able to read it normally, if not the problem is from the json not from the Android App.

Here is an example of request handling:

 RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
    JsonArrayRequest getRequest = new JsonArrayRequest(Request.Method.GET, "http://yourlink+parameters", new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {
            List<YourObject> reservations = null;
            try {

                YourObject= new ArrayList<YourObject>();
                for (int i = 0; i < response.length(); i++) {
                    JSONObject obj = response.getJSONObject(i);
                   YourObjectr = new YourObject(obj.getInt("id"), obj.getInt("user_id"),format.parse(obj.getString("date")), obj.getString("address"), obj.getString("description"));
                        }

                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            if (volleyError.networkResponse != null && volleyError.networkResponse.data != null) {
                VolleyError error = new VolleyError(new String(volleyError.networkResponse.data));
                volleyError = error;
                Log.i("error", "error :" + volleyError.getMessage());
                try {
                    JSONObject obj = new JSONObject(volleyError.getMessage());
                    if (obj.getString("error").equals("token_expired")) {
                        Intent i = new Intent(MainActivity.this, LoginActivity.class);
                        startActivity(i);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            } else {
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("connection problem")
                        .setMessage("check your connection")
                        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        })
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .show();
            }
        }
    });

    queue.add(getRequest);
查看更多
霸刀☆藐视天下
3楼-- · 2019-01-20 08:23

This is an example to work with JSONArray data and headers.

First create your own custom request type implementation:

public class JsonRequest extends JsonObjectRequest {

    public JsonRequest(int method, String url, JSONObject jsonRequest, Response.Listener
            <JSONObject> listener, Response.ErrorListener errorListener) {
        super(method, url, jsonRequest, listener, errorListener);
    }

    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));

            JSONObject jsonResponse = new JSONObject();
            jsonResponse.put("data", new JSONArray(jsonString));
            jsonResponse.put("headers", new JSONObject(response.headers));

            return Response.success(jsonResponse,
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }
}

and in your request code:

JsonRequest request = new JsonRequest
        (Request.Method.POST, URL_API, payload, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONArray data = response.getJSONArray("data");
                    JSONObject headers = response.getJSONObject("headers");
                } catch (JSONException e) {
                    Log.e(LOG_TAG, Log.getStackTraceString(e));
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(LOG_TAG, Log.getStackTraceString(error));
            }
        });

See more information about implementing your own custom request in the Volley documentation Implementing a Custom Request.

查看更多
虎瘦雄心在
4楼-- · 2019-01-20 08:34

To get the headers you need to override parseNetworkResponse() in your request.

for example the JsonObjectRequest:

public class MetaRequest extends JsonObjectRequest {

    public MetaRequest(int method, String url, JSONObject jsonRequest, Response.Listener
            <JSONObject> listener, Response.ErrorListener errorListener) {
        super(method, url, jsonRequest, listener, errorListener);
    }

    public MetaRequest(String url, JSONObject jsonRequest, Response.Listener<JSONObject>
            listener, Response.ErrorListener errorListener) {
        super(url, jsonRequest, listener, errorListener);
    }

    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
            JSONObject jsonResponse = new JSONObject(jsonString);
            jsonResponse.put("headers", new JSONObject(response.headers));
            return Response.success(jsonResponse,
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }
}
查看更多
登录 后发表回答