因为要写一个接口用于接收报文,以及返回报文都用GBK格式,代码如下:
public void returnMa(HttpServletRequest servletRequest, HttpServletResponse response)throws Exception{
InputStream inputStream = servletRequest.getInputStream();
SAXReader saxReader = new SAXReader();
logger.info("插入的数据未编译前为{}", inputStream.toString());
// InputStreamReader strInStream = new InputStreamReader(inputStream, "GBK");
Document read1 = saxReader.read(inputStream);
Element rootElement = read1.getRootElement();
HashMap<String, String> map = new HashMap();
xmlToMap(rootElement,map);
Document document = DocumentHelper.createDocument();
document.setXMLEncoding("GBK");
Element packet = document.addElement("PACKET");
Element head = packet.addElement("HEAD");
Element uuid = head.addElement("UUID");
uuid.addText(map.get("UUID")==null?"":map.get("UUID"));
if(i>0){
Element returncode = head.addElement("RETURNCODE");
returncode.addText("1");
Element returnmessage = head.addElement("RETURNMESSAGE");
returnmessage.addText("成功");
}else{
Element returncode = head.addElement("RETURNCODE");
returncode.addText("2");
Element returnmessage = head.addElement("RETURNMESSAGE");
returnmessage.addText("失败");
}
}else{
Element returncode = head.addElement("RETURNCODE");
returncode.addText("2");
Element returnmessage = head.addElement("RETURNMESSAGE");
returnmessage.addText("失败");
}
response.setCharacterEncoding("GBK");
response.setContentType("text/plain;charset=GBK");
//
response.getOutputStream().write(document.asXML().getBytes());
// String res=new String( document.asXML().getBytes("GBK),"utf-8");
// return res;
}
private static void xmlToMap(Element element, Map<String, String> map) {
map.put(element.getName().toUpperCase(), element.getTextTrim());
Iterator iterator = element.elementIterator();
while (iterator.hasNext()) {
xmlToMap((Element) iterator.next(), map);
}
}
完成之后本地测试正常,放到服务器上测试出现乱码
HTTP/1.1 200
Content-Type: text/plain;charset=GBK
Content-Length: 144
Date: Thu, 01 Aug 2019 09:27:58 GMT
<?xml version="1.0" encoding="GBK"?>
<PACKET><HEAD><UUID>0</UUID><RETURNCODE>1</RETURNCODE><RETURNMESSAGE>鎴愬姛</RETURNMESSAGE></HEAD></PACKET>
后修改文件.profile添加
export LC_ALL="zh_CN.GBK"
export LANG="zh_CN.GBK"
乱码问题解决
HTTP/1.1 200
Content-Type: text/plain;charset=GBK
Content-Length: 142
Date: Thu, 01 Aug 2019 09:37:09 GMT
<?xml version="1.0" encoding="GBK"?>
<PACKET><HEAD><UUID>0</UUID><RETURNCODE>1</RETURNCODE><RETURNMESSAGE>成功</RETURNMESSAGE></HEAD></PACKET>
问题原因看网上说的是因为window的编码格式GBK,Linux的编码格式为UTF-8所以修改Linux编码格式就解决了