为什么在StringReader read()中得到IndexOutOfBoundsException?

时间:2018-12-18 08:50:39

标签: android retrofit2 indexoutofboundsexception okhttp3 stringreader

in this example一样,我想用一个简单的base64字符串来衡量我的上传进度,而不是图像。该字符串通常约为。长度为500 kB。

在示例中,我从OkHttp3的RequestBody扩展了Body并重写:

@Override
    public void writeTo(BufferedSink sink) throws IOException {
        StringReader in = new StringReader(base64);
        char[] buffer = new char[2048];
        int uploaded = 0;
        try {
            int read;
            while ((read = in.read(buffer, uploaded, buffer.length)) != -1) {
                uploaded += read;
                System.out.println("BUFFER " + buffer);
                sink.write(new String(buffer).getBytes(), 0, read);
                this.callback.onProgressUpdate(uploaded);
            }
        } catch(IndexOutOfBoundsException e) {
            System.err.println("IndexOutOfBoundsException uploaded " + uploaded + " , buffer " + buffer.length + " from total " + base64.length());
        } finally {
            in.close();
            this.callback.onFinish(uploaded);
        }
}

我可以成功读取前2048个字符,但是在while循环的第二轮中,我得到了IndexOutOfBoundsException吗?

0 个答案:

没有答案