zoukankan      html  css  js  c++  java
  • DataOutputStream的writeBytes(String s)


    最近,在关于网络请求中有用到DataOutputStraem中的writeBytes()方法,然而就是这个问题,导致了传输中文时就出现问题,着实困扰了很长一段时间。
    后来,服务器端同事建议我使用DataOutputStream.write(byte[])方法,发现问题解决了。起初认为是编码问题,后来认真研究了一下,发现了问题的原因。

    首先,先看一下DataOutputStream的writeBytes方法的实现。


    /**
         * Writes out the string to the underlying output stream as a 
         * sequence of bytes. Each character in the string is written out, in 
         * sequence, by discarding its high eight bits. If no exception is 
         * thrown, the counter <code>written</code> is incremented by the 
         * length of <code>s</code>.
         *
         * @param      s   a string of bytes to be written.
         * @exception  IOException  if an I/O error occurs.
         * @see        java.io.FilterOutputStream#out
         */
     
     public final void writeBytes(String s) throws IOException {
    	int len = s.length();
    	for (int i = 0 ; i < len ; i++) {
    	    out.write((byte)s.charAt(i));
    	}
    	incCount(len);
        }


    问题出现了,int len = s.length();这就验证了问题的表象,对于英文的字符串都是正常的,对于某些中文就出现问题了。
    这个writeBytes的方法,对于单字节的文字(多为英文)是没有问题的,因为当单字节是string.length()和string.getBytes().length是相同的,而多字节不同。
    所以,对于存在多字节的请求,不要使用writeBytes(String)的方法,推荐使用write(byte[])等方法

  • 相关阅读:
    CSS换行和省略号
    html+canvas实现很真实的下雨雨落
    CSS取消鼠标点击事件
    js某时间与当前时间差
    uniapp微信小程序canvas隐藏
    canvas生成圆图和微信小程序canvas圆图
    uniapp微信小程序canvas绘图插入网络图片不显示
    uniapp微信小程序分享(朋友圈分享)
    关于sure 等同根词的演化
    Stress and rhythm in English pronunciation
  • 原文地址:https://www.cnblogs.com/jiangu66/p/3172266.html
Copyright © 2011-2022 走看看