我在我当前的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;
}
这是正确的做法吗?