我试图通过远程文件读取范围。
根据以下跟踪声音,setRequestProperty没有执行其工作(InputStream Length对我来说只有一个......第一个???)?
Task Runnable ID = 0 --> Requested Range Property = {Range=[bytes=0-93969]} Task Runnable ID = 1 --> Resquested Range Property = {Range=[bytes=93970-187939]} Task Runnable ID = 2 --> Requested Range Property = {Range=[bytes=187940-281909]} Task Runnable ID = 3 --> Resquested Range Property = {Range=[bytes=281910-375883]} Task Runnable ID = 0 --> InputStream Lenght = 93970 / StartByte = 0 / CurrentByte = 0 / EndByte = 93969 Task Runnable ID = 1 --> InputStream Length = 375883 / StartByte = 93970 / CurrentByte = 93970 / EndByte = 187939 Task Runnable ID = 3 --> InputStream Length = 375883 / StartByte = 281910 / CurrentByte = 281910 / EndByte = 375883 Task Runnable ID = 2 --> InputStream Length = 375883 / StartByte = 187940 / CurrentByte = 187940 / EndByte = 281909
我的代码是:
public class TaskRunnable implements Runnable { private static final int BUFFER_SIZE = 4092; private long startByte; private long currentByte; private long endByte; private Task task; private static int idCounter = 0; private int id; @SuppressWarnings("unused") private TaskRunnable() { } public TaskRunnable(Task task, long startByte, long endByte) { this.startByte = startByte; this.endByte = endByte; this.task = task; this.currentByte = startByte; this.id = idCounter++; } @Override public void run() { Thread.currentThread().setName("Download Runnable"); Authenticator authenticator = task.getManager().getAuthenticator(); if (authenticator != null) { Authenticator.setDefault(authenticator); } File targetFile; synchronized (this) { targetFile = new File(task.getTargetFile().getAbsolutePath()); } BufferedInputStream bufferedInputStream = null; byte[] buf = new byte[BUFFER_SIZE]; URLConnection urlConnection = null; try { URL _url = new URL(task.getSourceFileUrl().toString()); Proxy proxy = task.getManager().getProxy(); if (proxy != null) { urlConnection = _url.openConnection(proxy); } else { urlConnection = _url.openConnection(); } urlConnection.setRequestProperty("Range", "bytes=" + currentByte + "-" + endByte); System.out.println("Task Runnable ID = " + id + " --> Requested Range Property = " + urlConnection.getRequestProperties().toString()); bufferedInputStream = new BufferedInputStream(urlConnection.getInputStream()); int len = 0; while (bufferedInputStream.read() != -1) { len++; } System.out.println("Task Runnable ID = " + id + " --> InputStream Length = " + len + " / StartByte = " + startByte + " / CurrentByte = " + currentByte + " / EndByte = " + endByte); bufferedInputStream.close(); } catch (IOException e) { e.printStackTrace(); } }
显然这是我的错,但却无法弄清楚出了什么问题。非常欢迎。谢谢!
注意:如果使用相同的代码但基于单线程,则一切正常。
答案 0 :(得分:0)
我怀疑内部URLConnection状态的并发修改。您是否尝试过调用URLConnection.setUseCaches(false)
?
<强>更新强>
影响可能重用URLConnection
个对象的另一个全局缓存是ResponseCache。您应该在初始化时通过执行
ResponseCache.setDefault(null);