Spring 处理压缩和解压缩请求

核心是压缩和解压。


压缩代码:

public byte[] compress(String str) {
if (str == null || str.length() == 0) {
return null;
}
ByteArrayOutputStream out = null;
GZIPOutputStream gzip = null;
byte[] compress;
try {
out = new ByteArrayOutputStream();
gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes("utf-8"));
gzip.close();
compress = out.toByteArray();
return compress;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != out) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}



调用代码这模拟将压缩后的byte[]数组作为请求Body给另外的微服务的url


public String getTollJsonByTile(String coordiate) throws Exception {

/* protobuffer对字符串压缩效果一般,所以还是用GZIP进行压缩。
FmbRequstPb.FmbRequstPbInner.Builder request = FmbRequstPb.FmbRequstPbInner.newBuilder();
request.setCoordinate(coordiate);
request.setCarid(123);
byte[] sentByteArray = request.build().toByteArray();
*/

HttpHeaders requestHeaders = new HttpHeaders();
// Accept
//requestHeaders.set("Accept", "text/");
requestHeaders.set("Accept-Charset", "utf-8");

//对字符串进行压缩
byte[] test = compress(coordiate);


// String sst1= restTemplate.postForObject("http://SYNC/sync/user/find/modeid?parm={parm}",null,String.class,"abcde");
String sst2 = restTemplate.postForObject("http://SYNC/sync/adas/pbf/warn", test, String.class);

return sst2;
}


SYNC这个微服务的接收controller

 @RequestMapping(value = "/adas/pbf/warn",method = RequestMethod.POST)
public ResponseEntity getBrotocalBuffer(HttpServletRequest rq,@RequestBody byte[] coordinates) throws IOException {

//FmbRequstPb.FmbRequstPbInner req = FmbRequstPb.FmbRequstPbInner.parseFrom(coordinates);

//return ResponseEntity.ok(req.toByteArray());
//解压缩
String ss = uncompress(coordinates);


return ResponseEntity.ok(ss);

}



解压缩代码:

public String uncompress(byte[] str) {
if (str == null || str.length== 0) {
return null;
}
ByteArrayOutputStream out = null;
ByteArrayInputStream in = null;
GZIPInputStream gzip = null;
String uncompress = "";
try {
out = new ByteArrayOutputStream();
in = new ByteArrayInputStream(str);
gzip = new GZIPInputStream(in);
byte[] buffer = new byte[1024];
int offset = -1;
while ((offset = gzip.read(buffer)) != -1) {
out.write(buffer, 0, offset);
}
uncompress = out.toString("utf-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != gzip) {
try {
gzip.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != in) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != out) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return uncompress;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值