多线程下载时HTTP response code: 416 解决方案

来源:互联网 发布:安卓免费源码分享网站 编辑:程序博客网 时间:2024/05/16 14:50

今天用java写的多线程下载报错,找了很久,发现是第一次请求服务器时响应码正常,开启多线程部分的响应码为416,响应码对应的意思可以去这里看看点击打开链接。主要意思就是public voidsetRequestProperty (String field,String newValue)出现了错误,设置的下载字节范围和访问文件大小有出入,要么就是上面确认各个线程的下载范围出现问题,要么就是该语句没用对。将之前的每个线程下载字节范围都打印出来发现没问题。后来查看setRequestProperty相关资料发现是setRequestProperty("Range", "bytes:" + threadStart + "-" + threadEnd)这里出错了,bytes后面应该是=号而不是:

附上没有完成断点下载的多线程下载代码.

(我用的是某马的74期的视频学习的,而他的代码用的是:却可以运行,有点郁闷,,还有他的getFileName()方法中获取/的索引后没有+1就截取文件名得到的是/feiq.exe, 那也是错误的,后面运行时会报错拒绝访问)


package com.lyle.study;import java.io.File;import java.io.InputStream;import java.io.RandomAccessFile;import java.net.HttpURLConnection;import java.net.URL;public class UpDownload1 {public static String path = "http://192.168.56.1:8080/itheima74/feiq.exe";public static int threadCount = 3;public static void main(String[] args) {try {URL url = new URL(path);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("GET");connection.setConnectTimeout(1000 * 10);if (connection.getResponseCode() == 200) {long length = connection.getContentLength();RandomAccessFile randomAccessFile = new RandomAccessFile(new File(getFileName()),"rw");randomAccessFile.setLength(length);randomAccessFile.close();long threadSize = length / threadCount;for (int i = 0; i < threadCount; i++) {int threadId = i;long threadStart = threadId * threadSize;long threadEnd = (threadId == threadCount - 1 ? length - 1 : (threadId + 1)* threadSize - 1);new DoThreadOpen(threadStart, threadEnd).start();}}} catch (Exception e) {e.printStackTrace();}}public static class DoThreadOpen extends Thread {private long threadStart;private long threadEnd;public DoThreadOpen(long threadStart, long threadEnd) {this.threadEnd = threadEnd;this.threadStart = threadStart;}@Overridepublic void run() {try {URL url = new URL(path);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("GET");connection.setConnectTimeout(1000 * 10);connection.setRequestProperty("Range", "bytes=" + threadStart + "-" + threadEnd);int code = connection.getResponseCode();if (code == 206) {InputStream inputStream = connection.getInputStream();RandomAccessFile randomAccessFile = new RandomAccessFile(new File(getFileName()), "rw");randomAccessFile.seek(threadStart);byte[] buffer = new byte[1024];int len;while ((len = inputStream.read(buffer)) != -1) {randomAccessFile.write(buffer, 0, len);}inputStream.close();randomAccessFile.close();}} catch (Exception e) {e.printStackTrace();}}}private static String getFileName() {return path.substring(path.lastIndexOf("/") + 1);}}


0 0