Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

java - How to send httpRequest to server with GZIP DATA

I have a json file that I am sending to the server as a POST but it has to be gzipped

I dont know how to do it

I found the potential solution here GZip POST request with HTTPClient in Java

but I dont know how to merge the methodology they used in the second part of the answer with my makeHttpRequest method (they are using a multipart entity and Im using a urlencoded entity)

EDIT: Here is how I get jsonAsBytes

public static byte[] stringToGZIPByteArray (String string) {
    Log.d("string to be gzipped", string);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gzos = null;

    try {
        gzos = new GZIPOutputStream(baos);
        gzos.write(string.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (gzos != null) {
            try { 
                gzos.close();
                } catch (IOException ignore) {

                };
        }
    }

    return baos.toByteArray();
} // End of stringToGZIPByteArray

This is where I use that method

jsonParser.sendGzippedJSONviaHTTP(context, API.JSON_ACCEPT,    UtilityClass.stringToGZIPByteArray(jsonObject.toString()), context.getResources());

and this is sendGzippedJSONviaHTTP

public JSONObject sendGzippedJSONviaHTTP(Context context, String url, byte[] gzippedJSON, Resources res) {

    if (httpClient == null) {
        try {
            httpClient = new HttpClientBuilder().setConnectionTimeout(10000) 
                    .setSocketTimeout(60000) //
                    .setHttpPort(80)//
                    .setHttpsPort(443)//
                    .setCookieStore(new BasicCookieStore())//
                    .pinCertificates(res, R.raw.keystore, null) //
                    .build();
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // Making HTTP request
    try {

        // request method is POST
        // defaultHttpClient

        HttpPost httpPost = new HttpPost(url);


        httpPost.setHeader("Content-Encoding", "gzip");
        httpPost.setHeader("Content-Type", "application/json");

        httpPost.setEntity(AndroidHttpClient.getCompressedEntity(gzippedJSON, context.getContentResolver()));


        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        inputStream = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "
");
        }
        inputStream.close();
        reader.close();
        json = sb.toString();
    } catch (ClientProtocolException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    // try parse the string to a JSON object
    try {
        jsonObject = new JSONObject(json);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    // return JSON String
    return jsonObject;

} // End of makeHttpRequest
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Take a look at AndroidHttpClient. You can use it instead of appache's DefaultHttpClient. It has a static method getCompressedEntity(byte[] data, ContentResolver resolver)

So, you can write:

 HttpPost httpPost = new HttpPost(url);
 post.setEntity( AndroidHttpClient.getCompressedEntity( jsonAsBytes, null ) );
 httpClient.execute(httpPost);

UPDATE:

this is the code from AndroidHttpClient:

public static AbstractHttpEntity getCompressedEntity(byte data[], ContentResolver resolver)
        throws IOException {
    AbstractHttpEntity entity;
    if (data.length < getMinGzipSize(resolver)) {
        entity = new ByteArrayEntity(data);
    } else {
        ByteArrayOutputStream arr = new ByteArrayOutputStream();
        OutputStream zipper = new GZIPOutputStream(arr);
        zipper.write(data);
        zipper.close();
        entity = new ByteArrayEntity(arr.toByteArray());
        entity.setContentEncoding("gzip");
    }
    return entity;
}

should give you some insights


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...