解压:
public static String analyzeGetGzip(String url,String param) throws Exception{
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("Pragma", "no-cache");
connection.setConnectTimeout(5000);
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
InputStream urlStream = new GZIPInputStream(connection.getInputStream());
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(urlStream));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
压缩方法:
public static void responseXmlWithGzip(HttpServletResponse response, String docXML){
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(bout);
gzip.write(docXML.getBytes("UTF-8"));
gzip.flush();
gzip.close();
byte[] buf = bout.toByteArray();
//服务器传回数据的类型和长度
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Content-Encoding","gzip");
response.setHeader("Content_Length",buf.length+"");
response.getOutputStream().write(buf);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}