android-添加标头谷歌排球请求吗?
作者:互联网
好吧,我是这个论坛的新手,如果可以的话,请帮助我.我搜索了但我找不到如何向齐射请求添加标头.我有此代码,我想添加accept-encoding:gzip和api密钥.我将感谢您的帮助.这是代码:
type = "cafe";
url = "https://maps.googleapis.com/maps/api/place/search/json?location=" + Global.location + "&radius=500&types=" + type + "&sensor=true&key="+placesKey;
RequestQueue rq = Volley.newRequestQueue(context);
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
List<Review> reviews = new ArrayList<Review>();
reviews = Parsing.ParseReviews(response);
}
}, new Response.ErrorListener() {
@Override
public void one rrorResponse(VolleyError error) {
Toast.makeText(context, error.toString(), Toast.LENGTH_SHORT).show();
}
});
rq.add(jsonRequest);
解决方法:
JsonObjectRequest jsObjectRequest = new JsonObjectRequest(
Request.Method.POST,
url,
jsonRequest,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, "Respuesta en JSON: " + response.toString());
}
},
new Response.ErrorListener() {
@Override
public void one rrorResponse(VolleyError error) {
Log.d(TAG, "Error Respuesta en JSON: " + error.toString());
}
}
){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
//return super.getHeaders();
Map<String, String> params = new HashMap<>();
params.put("Content-Encoding", "gzip");
return params;
}
};
VolleySingleton.getInstance(context).addToRequestQueue(jsObjectRequest);
您可以在getHeaders()中添加标题.
编辑:如何在gzip中编码
JsonObjectRequest jsObjectRequest = new JsonObjectRequest(
/*same here*/
){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Encoding", "gzip");
return params;
}
@Override
public byte[] getBody() {
try{
return Encode.gzip(super.getBody());
}catch(IOException e){
Log.d(TAG, e.getMessage());
return super.getBody();
}
}
};
VolleySingleton.getInstance(context).addToRequestQueue(jsObjectRequest);
编码GZip
public static byte[] gzip(byte[] bytes) throws IOException{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = null;
try {
gzos = new GZIPOutputStream(baos);
gzos.write(bytes);
}finally {
if (gzos != null){
try{
gzos.close();
}catch (IOException ignore) {}
}
}
return baos.toByteArray();
}
标签:encoding,request,android-volley,header,android 来源: https://codeday.me/bug/20191122/2061603.html