GzipUtils工具类
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GzipUtils {
/**
* 压缩
* 在使用GZIP进行压缩和解压时,如果压缩后的字节数组在传输过程中发生改变就会导致此异常的发生,
* 所以如果不是直接传输压缩后的字节数组而是字符串时,在转换为字符串时,一定要使用ISO-8859-1这样的单字节编码,
* 否则在将字符串转换为字节数组时会导致节数组产生变化,从而产生该异常。
* @param str
* @return
* @throws IOException
*/
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();
return out.toString("ISO-8859-1"); // UTF-8 ISO-8859-1
}
/**
* 解压缩
* 在使用GZIP进行压缩和解压时,如果压缩后的字节数组在传输过程中发生改变就会导致此异常的发生,
* 所以如果不是直接传输压缩后的字节数组而是字符串时,在转换为字符串时,一定要使用ISO-8859-1这样的单字节编码,
* 否则在将字符串转换为字节数组时会导致节数组产生变化,从而产生该异常。
* @param str
* @return
* @throws IOException
*/
public static String uncompress(String str) throws IOException {
if (str == null || str.length() == 0) {
return str;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = new ByteArrayInputStream(
str.getBytes("ISO-8859-1"));
GZIPInputStream gunzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
int n;
while ((n = gunzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
}
// toString()使用平台默认编码,也可以显式的指定如toString("GBK")
return out.toString();
}
/**
* 把字符串压缩成zip字节流
*
* @param str
* @return
*/
public static byte[] compressByte(String str) {
if (str == null || str.length() == 0) {
return null;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip;
try {
gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes(StandardCharsets.UTF_8));
gzip.close();
} catch (Exception e) {
e.printStackTrace();
}
return out.toByteArray();
}
/**
* 把zip字节流解析成字符串
*
* @param str
* @return
* @throws IOException
*/
public static String uncompressbyte(byte[] str) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(str))) {
int b;
while ((b = gis.read()) != -1) {
baos.write((byte) b);
}
} catch (Exception e) {
e.printStackTrace();
}
return new String(baos.toByteArray(), StandardCharsets.UTF_8);
}
}
发送gzip压缩数据
@GetMapping("/testRestTempPost")
@ApiOperation(value = "测试Post发送压缩数据到东软")
public String RestTempPost() throws IOException {
String sendMsg = "修改密码\n" +
"修改用户名密码\n" +
"禁用启用\n" +
" 用户名\n" +
" 身份证号";
sendMsg = JsonUtils.toString(huanyaUserService.getMessage());
String url = "http://192.168.1.55:8999/dataGet/getMessageCS";
LinkedMultiValueMap<String, String> header = new LinkedMultiValueMap<>();
header.add("Content-Type", "application/json"); // 在传送String时候需要改成charset=ISO-8859-1
header.add("Content-Encoding", "gzip");
header.add("Accept", "application/json");
// 发送byte[]
byte[] gzipEncrypt = GzipUtils.compressByte(sendMsg);
// base64编码
// byte[] encodeBase64 = Base64.encodeBase64(gzipEncrypt);
org.springframework.http.HttpEntity<byte[]> httpEntity =
new org.springframework.http.HttpEntity(gzipEncrypt, header);
// 调用String转换发送gzip
StringEntity data = new StringEntity(GzipUtils.compress(sendMsg),
Charset.forName("ISO-8859-1"));
// org.springframework.http.HttpEntity<String> httpEntity =
// new org.springframework.http.HttpEntity(GzipUtils.compress(sendMsg), header);
ResponseEntity< String > exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
String returnString = exchange.getBody();
// log.info("返回数据-------------------------------:"+returnString);
return "ok";
}
接收gzip数据
@PostMapping("/getMessageCS")
@ApiOperation(value = "模拟接口")
public String getMessageCS(HttpServletRequest request, HttpServletResponse response) throws IOException {
log.info("进入接收接口!");
String acceptjson = "";
String contentEncoding = request.getHeader("Content-Encoding");
// byte方式接收
// if (null != contentEncoding && contentEncoding.indexOf("gzip") != -1) {
// int totalBytes = request.getContentLength();
// System.out.println("当前数据总长度:" + totalBytes);
// DataInputStream dis = new DataInputStream(request.getInputStream());
// ByteArrayOutputStream baot = new ByteArrayOutputStream();
// byte[] bytes = new byte[1024]; // 定义一个数组 用来读取
// int n = 0;// 每次读取输入流的量
// while ((n = dis.read(bytes)) != -1) {
// baot.write(bytes); // 将读取的字节流写入字节输出流
// }
// byte[] outbyte = baot.toByteArray();// 将字节输出流转为自己数组
// acceptjson = GzipUtils.uncompressbyte(outbyte);
// log.info("返回数据:"+acceptjson);
// baot.close();
// dis.close();
//
// }
// return acceptjson;
// String 方式接收
if (null != contentEncoding && contentEncoding.indexOf("gzip") != -1) {
ServletInputStream inputStream = request.getInputStream();
if (inputStream !=null) {
GZIPInputStream gzis = new GZIPInputStream(inputStream);
InputStreamReader reader = new InputStreamReader(gzis);
BufferedReader br = new BufferedReader(reader);
StringBuffer sb = new StringBuffer("");
String temp;
while ((temp = br.readLine()) != null) {
sb.append(temp);
}
br.close();
acceptjson = sb.toString();
}
}else{
acceptjson = "no compress...";
}
log.info("返回数据:"+acceptjson);
return acceptjson;
}