读取使用DataOutputStream writeUTF()方法发送的okio上的UTF字符串

时间:2016-01-28 15:33:17

标签: java android utf-8 okhttp okio

我在我当前的android项目中使用okhttp和okio来获取和读取我发送的一些二进制流,在流中我使用方法发送一些UTF值

DataOutputStream.writeUTF().

“okhttp”为您提供了2个选项,可以获取inputStream,因此您可以直接使用方法DataInputStream.readUTF()。

另一个选择是将流作为BufferedSource并使用其方法读取数据,我很惊讶读取UTF的方法需要您提供字节数。

String readUtf8(long byteCount)

读取来自服务器的UTF我添加了以下方法

public static String readUtf(BufferedSource bufferedSource)throws IOException {
       int length =  readShortAsUnsignedInt(bufferedSource);
       return  bufferedSource.readUtf8(length);
    }

    public static int readShortAsUnsignedInt(BufferedSource bufferedSource)throws IOException {
        return bufferedSource.readShort() & 0xffff;
    }

这是正确的做法吗?

0 个答案:

没有答案