java处理接收inputstream中传来的中文字,出现某个字乱码问题

1.第一种情况

服务器和客户端编码不统一造成中文乱码,当服务器返回数据是UTF-8格式时,客户端在读取输入流时,需要将其转换成UTF-8格式,请看客户端部分代码:

………………..省略部分代码………………    
// 设置URL并且打开连接    
url = new URL("http://192.168.1.7:8080/exa/zh_cn");    
httpurlconnection = (HttpURLConnection) url.openConnection();    
//得到输入流并转换为字符串    
inputStream = httpurlconnection.getInputStream();    
String strResult="";    
byte[] b = new byte[1024];    
int i = 0;    
while ((i = inputStream.read(b)) != -1) {    
    strResult+=new String(b,"utf-8");    
    b = new byte[1024];    
}     
//显示到控件上    
textView_1.setText(strResult);    
………………省略部分代码………………    

代码中关键代码是,new String(b,”utf-8”),将byte数组转换成UTF-8格式的字符串,结果如图10-17所示。

当改成new String(b,”gb2312”)时得到结果如图10-18所示。

如何避免中文乱码问题,首先,不要频繁转码和漫无目的转码,这样转来转去最后自己也不知道转到哪里去了,其次,尽量使客户端程序的编码和服务器编码统一,再次避免用字节的方式去读取中文和操作中文字符串,因为一个汉字占两个字节,稍不注意开发过程中就会出现读取一个字节,造成读取了半个字,就会出现乱码。

2.第二种情况

中文汉字中出现少部分中文乱码。这种现象看起来很怪异,往往在开发过程中,读者都有可能这样操作了,但没有发现。这种现象是怎么造成的呢?先看例子程序。

实例:

读取文件的核心代码如下(为了测试多一些的汉字,本例将把很多汉字写在test.txt里放在assets文件夹下):
[java] view plain copy

………………..省略部分代码………………    
inputStream = this.getAssets().open("test.txt");    
byte buffer[] = new byte[100];    
StringBuffer sb = new StringBuffer();    
int i = 0;    
while ((i = inputStream.read(buffer)) != -1) {    
    sb.append(new String(buffer, 0, i));    
}    
textView_1.setText(sb.toString());    
………………..省略部分代码………………   

由上述代码产生的效果如图10-19所示。

部分乱码的现象出现了,原因我先不讲,先改动代码再看看效果。把byte buffer[] = new byte[100]改成byte buffer[] = new byte[inputStream.available()],运行后得到的效果如图10-20所示。

思考一下:100和inputStream.available()的区别,就会出现中文部分乱码的问题?原因是有可能在读取100个字节的时候正好遇到一个汉字的前半个字节,后100个字节的第一位置的字节也是这个字的后半个字节,半个字节是汉字吗?这样当然会出现乱码了。把字节的数组直接设置成输入流的长度,在读取的时候,一次性读取,那么就不会出现所谓的半个字的现象,当然也不会出现乱码的问题了。

还有一个解决办法,就是不以字节的方式读取文件,以字符的方式读取,一个字符装一个汉字是合法的,看一下代码

[java] view plain copy

………………..省略部分代码………………    
inputStream = this.getAssets().open("test.txt");    
StringBuffer sb = new StringBuffer();    
InputStreamReader isr=new InputStreamReader(inputStream);    
char buf[] = new char[20];    
int nBufLen = isr.read(buf);    
while(nBufLen!=-1){    
    sb.append(new String(buf, 0, nBufLen));    
    nBufLen = isr.read(buf);    
}    
textView_1.setText(sb.toString());    
………………..省略部分代码………………    

以上是网友的例子,看到点后,博主自己解决了问题,哈哈哈哈哈

ps:这是处理完后的方法。
`public static String sendPost(String url, String param) {
DataOutputStream out = null;
BufferedReader reader = null;
StringBuffer result = new StringBuffer(“”);
try {
//创建连接
URL realUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod(“POST”);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);

            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            connection.setRequestProperty("Accept-Charset", "utf-8");

// connection.setConnectTimeout(3000); //3秒连接超时
// connection.setReadTimeout(3000); //3秒读取超时
connection.setRequestProperty(“Charset”,”utf-8”);
connection.connect();

            //POST请求
            out =  new DataOutputStream(connection.getOutputStream());
            out.writeBytes(param);
            out.flush();
           // out.write(param.getBytes());

            //读取响应
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
            //字符形式读取,避免中文字符出现部分乱码问题
            char buf[] = new char[20];
            int nBufLen = reader.read(buf);    
            while(nBufLen!=-1){    
                result.append(new String(buf, 0, nBufLen));    
                nBufLen = reader.read(buf);    
            }  

            // 断开连接
            connection.disconnect();
        } catch (UnsupportedEncodingException e) {
            System.out.println("Message=="+e.getMessage());
           // e.printStackTrace();
        } catch (IOException e) {
            System.out.println("Message=="+e.getMessage());
            //e.printStackTrace();
        }
     finally {  
          try {  
              if (out != null) {  

              }  
              if (reader != null) {  
                  reader.close();  
              }  
          } catch (IOException ex) {
              ex.printStackTrace();  
          }  
      }

     return result.toString();  
}`
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值