核心是压缩和解压。
压缩代码:
调用代码这模拟将压缩后的byte[]数组作为请求Body给另外的微服务的url
SYNC这个微服务的接收controller
解压缩代码:
压缩代码:
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;
}