I utilized the gzip algorithm to compress a JSON file, following this method (source: java gzip can't keep original file's extension name)
private static boolean compress(String inputFileName, String targetFileName){
boolean compressResult=true;
int BUFFER = 1024*4;
byte[] B_ARRAY = new byte[BUFFER];
FileInputStream fins=null;
FileOutputStream fout=null;
GZIPOutputStream zout=null;
try{
File srcFile=new File(inputFileName);
fins=new FileInputStream (srcFile);
File tatgetFile=new File(targetFileName);
fout = new FileOutputStream(tatgetFile);
zout = new GZIPOutputStream(fout);
int number = 0;
while((number = fins.read(B_ARRAY, 0, BUFFER)) != -1){
zout.write(B_ARRAY, 0, number);
}
}catch(Exception e){
e.printStackTrace();
compressResult=false;
}finally{
try {
zout.close();
fout.close();
fins.close();
} catch (IOException e) {
e.printStackTrace();
compressResult=false;
}
}
return compressResult;
}
The JSON content is returned as follows:
response.setHeader("Content-Type", "application/json");
response.setHeader("Content-Encoding", "gzip");
response.setHeader("Vary", "Accept-Encoding");
response.setContentType("application/json");
response.setHeader("Content-Disposition","gzip");
response.sendRedirect(filePathurl);
or
request.getRequestDispatcher(filePathurl).forward(request, response);
When attempting to access the JSON object using AJAX code like so:
$.ajax({
type : 'GET',
url : url,
headers : {'Accept-Encoding' : 'gzip'},
dataType : 'text',
The result displayed is binary data instead of the uncompressed JSON string. Any recommendations on how to resolve this issue? Keep in mind that the browsers I am using (Internet Explorer, Chrome, Firefox) support gzip, as all my static contents compressed by Apache are rendering correctly.