I have a large amount of data being sent from server to Javascript, which is taking quite a long time to load.
I was wondering how I can implement compression at server and decompression in Javascript. I would appreciate any help.
To compress your String you can use:
public static String compress(String str) throws IOException {
if (str == null || str.length() == 0) {
return str;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes());
gzip.close();
String outStr = out.toString("UTF-8");
return outStr;
}
GZIPOutputStream is from java.util.zip
Most browsers should be able to handle gzip compressed content without the need of manual decompression.
Docs: GZIPOutputStream
See Loading GZIP JSON file using AJAX if you're using Ajax for the data acquisition on the client-side. It is necessary to set the headers for your response as @hgoebl
mentioned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With