Android java.lang.IllegalArgumentException:byteCount

时间:2016-09-03 04:38:48

标签: 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)

如何解决? 谢谢

1 个答案:

答案 0 :(得分:0)

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

根据建议,请考虑使用okhttp-urlconnection之类的:

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