从凌空响应中获取标头 [英] Getting headers from a response in volley
问题描述
我正在使用 Volley,我想向服务器发出请求,该服务器在可见层"中返回一个 JSON(我可以在 Web 浏览器中看到它).我的问题是服务器还返回了我需要在我的应用程序中获取的标头信息,但我无法从请求中获取标头.
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)
有人知道如何实现吗?
推荐答案
要获取您需要在请求中覆盖 parseNetworkResponse()
的标头.
To get the headers you need to override parseNetworkResponse()
in your request.
例如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));
}
}
}
这篇关于从凌空响应中获取标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!