Cho*_*opi 14 android header android-volley
我正在使用Volley,我想向服务器发出请求,该服务器在"可变层"中返回一个JSON(我可以在Web浏览器中看到它).我的问题是服务器还返回我需要在我的应用程序中获取的标头信息,但我无法从请求中获取标头.
我已经搜索了很长时间但我没有找到任何有用的东西(只有在请求标题中添加数据,但没有从标题的响应中获取数据)
谁知道如何实现?
djo*_*djo 21
要获取标头,您需要parseNetworkResponse()在请求中覆盖.
例如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));
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个使用 JSONArray 数据和标头的示例。
首先创建您自己的自定义请求类型实现:
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));
}
}
}
Run Code Online (Sandbox Code Playgroud)
并在您的请求代码中:
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));
}
});
Run Code Online (Sandbox Code Playgroud)
在 Volley 文档实现自定义请求 中查看有关实现您自己的自定义请求的更多信息。
| 归档时间: |
|
| 查看次数: |
12759 次 |
| 最近记录: |