2013-10-07 56 views
3

好吧,我是這個論壇的新成員,如果你能幫助我的話。我搜索了,但我無法找到如何添加頭到凌空的請求。我有這個代碼,我想添加接受編碼: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 onErrorResponse(VolleyError error) { 
Toast.makeText(context, error.toString(), Toast.LENGTH_SHORT).show(); 

} 
}); 

rq.add(jsonRequest); 
+1

這是一個可能的重複。看看這裏的答案:http://stackoverflow.com/questions/17049473/how-to-set-custom-header-in-volley-request – SBerg413

回答

2
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 onErrorResponse(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(); 
}