java - 安卓 java.lang.IllegalArgumentException : byteCount

标签 java android inputstream httpurlconnection

我从这段代码中得到随机错误(不是所有连接)java.lang.IllegalArgumentException: byteCount < 0: -291674

URL connurl = new URL(newUrl);
conn = (HttpURLConnection) connurl.openConnection();
conn.setRequestProperty("User-Agent", "Android");
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if (finish != 0L)
    conn.setRequestProperty("Range", "bytes=" + finish + "-" + size);
conn.connect();
int getResponseCode = conn.getResponseCode();
String getContenttype = conn.getContentType();
int contentLenght = conn.getContentLength();
if (!StringUtils.startsWith(String.valueOf(getResponseCode), "20")) {
}
else if(StringUtils.startsWithIgnoreCase(getContenttype, "text/html")) {
}
else if(contentLenght < (size-finish)) {
}
else {
    ReadableByteChannel channel = Channels.newChannel(conn.getInputStream()); 
    accessFile = new RandomAccessFile(filePath, "rwd");
    accessFile.seek(finish);
    fileStream = new FileOutputStream(filePath, true);
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    byte[] data;
    int temp;
    while ((temp = channel.read(buffer)) > 0) { <-- error in this line
    }

错误:

java.lang.IllegalArgumentException: byteCount < 0: -1647333
    at com.android.okhttp.okio.RealBufferedSource.read(RealBufferedSource.java:46)
    at com.android.okhttp.internal.http.HttpConnection$FixedLengthSource.read(HttpConnection.java:418)
    at com.android.okhttp.okio.RealBufferedSource$1.read(RealBufferedSource.java:349)
    at java.io.InputStream.read(InputStream.java:162)
    at java.nio.channels.Channels$InputStreamChannel.read(Channels.java:306)

如何解决? 谢谢

最佳答案

这可能与该问题有关:https://github.com/square/okhttp/issues/3104

按照建议,考虑使用 okhttp-urlconnection,例如:

OkHttpClient okHttpClient = new OkHttpClient();
URL.setURLStreamHandlerFactory(new OkUrlFactory(okHttpClient));

关于java - 安卓 java.lang.IllegalArgumentException : byteCount,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39303278/

相关文章:

java - 如果我们只覆盖类中的 hashCode() 并在 Set 中使用它会发生什么?

java - 来自 InputStream 的文件路径/名称

java - 使用 ByteArrayInputStream 构造 ObjectInputStream 后没有可用字节

java - 无法将128分配给字节,为什么会出错而不是溢出?

java - 以java形式读取MySQL数据

java - 使用 hibernate 持久化到 mysql 时出错

java - 如何使用 SeekBar 以编程方式调整设备亮度?

java - 通过查看 RecyclerView 的值来查找 RecyclerView 行位置

android - 每 5 秒用字符串数组中的每个字符串更新 TextView

java - 读取输入流