用HttpURLConnection访问我自己写的servlet,出现乱码问题。
访问的代码如下:
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty(Constant.HEADER_X_APPID, "com.pingan.ai.aaa");
conn.setRequestProperty(Constant.HEADER_X_DEVICEID, "test_client");
long timestamp = new Timestamp(System.currentTimeMillis()).getTime();
conn.setRequestProperty(Constant.HEADER_X_TIMESTAMP, String.valueOf(timestamp));
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "中文");
jsonObject.put("cardNo", "29135791743");
String uft8Str = new String(jsonObject.toString().getBytes(),"UTF-8");
System.out.println("---utf8str--- "+ uft8Str);
String bodyStr = SignatureUtil.sha256(uft8Str);
conn.setRequestProperty("Authorization", SignatureUtil.getSignature(getMessage(timestamp, bodyStr), SECRET));
conn.connect();
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
//Writer out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
out.write(uft8Str.getBytes("UTF-8"));
out.flush();
servlet端接收数据如下:
BufferedReader tBufferedReader = new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8"));
StringBuffer inputsb = new StringBuffer();
String temp;
while ((temp = tBufferedReader.readLine()) != null) {
inputsb.append(temp);
}
LOGGER.info("the input str from inputstream is "+inputsb.toString());
String inputJson = new String(inputsb.toString().getBytes(), "UTF-8");
这段代码在我的开发环境没有问题,我用的Mac开发。项目打包成war,放到Linux环境下,接收的中文成了乱码,有没有高手帮看看,怎么回事。