在处理中文字符串的时候,如何处理�这个字符

首先需要明白�这个字符是什么意思,是怎么产生的
解释:从某编码向Unicode编码转化时,如果没有对应的字符,得到的将是Unicode的代码“\uffffd”,也就是�这个字符。

比如:服务器端用GB2312对响应的数据进行编码,而接收端使用默认UTF-8编码接收是对应不上的,就会出现这个符号。

解决方法
跟服务器端保持一致的接收编码即可,如:


    /**
     * 将响应实体拼接成字符串返回
     *
     * @param entity 响应实体
     * @return 实体字符串
     */
    private static String entity2String(HttpEntity entity) {
        StringBuilder content = new StringBuilder();
        try (InputStream inputStream = entity.getContent();
             InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"gb2312"); //这里的解析类型需要和服务器响应内容的Content-Type: text/html; charset=gb2312 里面的charset保持一致
             BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
            // 读取数据
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                content.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content.toString();
    }

符号解释引用处:
http://www.php.cn/php-weizijiaocheng-104615.html

猜你喜欢

转载自blog.csdn.net/fragrant_no1/article/details/83788560