2 chennei9527 chennei9527 于 2017.09.07 16:41 提问

java web在linux中的乱码问题

用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环境下,接收的中文成了乱码,有没有高手帮看看,怎么回事。

2个回答

Small_Mouse0
Small_Mouse0   Ds   Rxr 2017.09.07 16:44

linux下是用tomcat跑的??

是的话,,给tomcat配置中下面的标签加个编码

   <Connector  
                port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443"  
               URIEncoding="utf-8"/>
chennei9527
chennei9527 谢谢,是用的tomcat,这个配置项我也加了的。
3 个月之前 回复
wbzhang2010
wbzhang2010   2017.09.07 17:58

jsonObject.put("name", URLEncoder.encode("中文", "utf-8"));

Csdn user default icon
上传中...
上传图片
插入图片