如何在Android中使用Volley发布压缩后的JSON?

时间:2019-07-10 04:43:57

标签: java android-volley gzip

我必须在Android中使用Volley发送压缩的JSON数据。但是Volley只接受JSON对象。我需要做些什么来通过排球请求发送gzip压缩的json?

JSONObject名称=新的JSONObject();         尝试{

        name.put("name","hello");

    }catch(JSONException e){
        e.printStackTrace();
    }
    JSONObject data = new JSONObject();
    try{
        rrsrsData.put("data",name);

    }catch(JSONException e){

    }

   try{
        byte[] compressData = compress(data);
    }catch (Exception e){
        e.printStackTrace();
    }

公共静态字节[] compress(JSONObject对象)抛出异常{

   String str = object.toString();
    ByteArrayOutputStream obj=new ByteArrayOutputStream();
    GZIPOutputStream gzip = new GZIPOutputStream(obj);
    gzip.write(str.getBytes("UTF-8"));
    gzip.close();
    String outStr = obj.toString("UTF-8");
    System.out.println("Output String length : " + outStr.length());
    return obj.toByteArray();
}




    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST , url, compressData , new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

            Log.v("Json Sucess",response.toString());



        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            Log.v("Json Error",error.toString());

        }
    }) {

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap headers= new HashMap();
            headers.put("Content-Type","application/json");
            headers.put("User-Agent","RRSRS/214.204.1");
            headers.put("Content-Encoding", "gzip");


            //return super.getHeaders();
            return headers;
        }
    };

0 个答案:

没有答案