HTTP breakpoint download Client and server

Source: Internet
Author: User
Tags log log ranges rar

Client
Import Java.io.BufferedInputStream;
Import Java.io.File;
Import Java.io.RandomAccessFile;
Import java.net.HttpURLConnection;
Import Java.net.URL;

public class Arcsynchttpclient {
public static void Main (string[] args) throws Exception {


String strURL = "Http://localhost:8080/ArcSyncHttpDownload/httpServlet";
URL downurl = new URL (strurl);
HttpURLConnection cn = (httpurlconnection) downurl.openconnection ();
if (cn.getresponsecode () = = 200) {
InputStream is = Cn.getinputstream ();
int part_count = 10;

int contentlength = Cn.getcontentlength ();
System.out.println ("Cn.getcontentlength ():" +cn.getcontentlength ());
int firstlength = Contentlength/part_count;
System.out.println ("Firstlength ():" + firstlength);
Cn.disconnect ();
Part_count = 1;
for (int i = 1; i < part_count+1; i++) {
if (I==part_count) {
int lastlength = contentlength-firstlength* (part_count-1);
File SaveFile = new file ("E:/test/123", String.Format ("123_0%d.mp3", I));
Testdownload.download (Savefile.getname (), Savefile.getparent (),
strURL, (i-1) *firstlength, contentlength);
}else {
File SaveFile = new file ("E:/test/123", String.Format ("123_0%d.mp3", I));
Testdownload.download (Savefile.getname (), Savefile.getparent (),
strURL, (i-1) *firstlength, firstlength*i);
}

}
}
}

public static void Download (string fileName, String filepath,string remoteurl, long start, long end) {
byte[] buf = new byte[10240];
HttpURLConnection httpurlconnection;
URL url;
Bufferedinputstream bis;
int size;
Randomaccessfile Rndfile;
Download file
try {
url = new URL (remoteurl);
HttpURLConnection = (httpurlconnection) url.openconnection ();
Set User-agent
Httpurlconnection.setrequestproperty ("User-agent", "Net");
Set Resume Start
Httpurlconnection.setrequestproperty ("Range", "bytes=" + Start + "-" + end);
Get input stream
bis = new Bufferedinputstream (Httpurlconnection.getinputstream ());
Rndfile = new Randomaccessfile (filePath + "\ \" + FileName, "RW");
Rndfile.seek (0);
int i = 0;
while (size = Bis.read (BUF))! =-1) {
if (i >) break;
Rndfile.write (buf, 0, size);

i++;
}
System.out.println ("i=" + i);
Httpurlconnection.disconnect ();
Bis.close ();
Rndfile.close ();
} catch (Exception e) {
Todo:handle exception
E.printstacktrace ();
}
}

public static long Getremotefileszie (String URL) {
Long size = 0;
try {
HttpURLConnection Httpurl = (httpurlconnection) (new URL (URL)). OpenConnection ();
Size = Httpurl.getcontentlength ();
Httpurl.disconnect ();
} catch (Exception e) {
Todo:handle exception
E.printstacktrace ();
}
return size;
}

public static void Mergefiles (String outFile, list<string> files) {
FileChannel outchannel = null;
System.out.println ("Merge" + Files + "into" + outFile);
try {
Outchannel = new FileOutputStream (outFile). Getchannel ();
for (String f:files) {
FileChannel fc = new FileInputStream (f). Getchannel ();
Bytebuffer BB = bytebuffer.allocate (BUFSIZE);
while (Fc.read (BB)! =-1) {
Bb.flip ();
Outchannel.write (BB);
Bb.clear ();
}
Fc.close ();
}
System.out.println ("merged!!");
} catch (IOException IoE) {
Ioe.printstacktrace ();
} finally {
try {
if (Outchannel! = null) {
Outchannel.close ();
}
} catch (IOException ignore) {
}
}
}

}

Service side

Package Com.defonds.cds.common;


Import Java.io.BufferedOutputStream;
Import Java.io.File;
Import java.io.IOException;
Import Java.io.OutputStream;
Import Java.io.RandomAccessFile;

Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

HTTP Breakpoint Continuation Demo (Client Test tool: Express, Thunderbolt)
public class Arcsynchttpdownloadservlet extends HttpServlet {
Private static final long serialversionuid = 1L;
Final static log log = Logfactory.getlog (Arcsynchttpdownloadservlet.class);

@Override
protected void Doget (HttpServletRequest req, HttpServletResponse resp)
Throws Servletexception, IOException {
This.dopost (req, resp);
}

@Override
protected void DoPost (HttpServletRequest request, httpservletresponse response) {
File DownloadFile = new ("E:/test/123.mp3");//Files to download
Long filelength = Downloadfile.length ();//Record file size
System.out.println ("Filelength:" +filelength);
Long pastlength = 0;//record downloaded file size
int rangeswitch = 0;//0: full-text download from scratch; 1: Download starting from a byte (bytes=27000-); 2: Download from start of a byte to end of a byte (bytes=27000-39000)
Long tolength = 0;//records the last byte offset of the byte segment that the client needs to download (for example, bytes=27000-39000, this value is 39000)
Long ContentLength = 0;//The total number of bytes requested by the client
String rangebytes = "";//record the contents of the client's form such as "bytes=27000-" or "bytes=27000-39000"
Randomaccessfile RAF = null;//is responsible for reading the data
OutputStream OS = null;//Write Data
OutputStream out = null;//buffer
byte b[] = new byte[1024];//staging container

if (Request.getheader ("Range") = null) {//client requests the start byte of the downloaded file block
Response.setstatus (Javax.servlet.http.HttpServletResponse.SC_PARTIAL_CONTENT);
System.out.println ("Request.getheader (\" range\ ") =" + Request.getheader ("Range");
Rangebytes = Request.getheader ("Range"). ReplaceAll ("bytes=", "" ");
int index = rangebytes.indexof ('-');
int length = Rangebytes.length ()-1;
if (index = = 1) {//bytes=969998336-
Rangeswitch = 1;
rangebytes = rangebytes.substring (0, Rangebytes.indexof ('-'));
String temp0 = rangebytes.substring (0,rangebytes.indexof ('-'));
String Temp2 = rangebytes.substring (Rangebytes.indexof ('-') + 1, rangebytes.length ());
Pastlength = Long.parselong (Temp0.trim ());
if ("". Equals (Temp2)) {
ContentLength = filelength-pastlength + 1;//The client is requesting bytes after 969998336
}else {
Tolength = Long.parselong (TEMP2);//bytes=1275856879-1275877358, to the end of the 1,275,877,358th byte
ContentLength = tolength-pastlength + 1;//The client requested a byte between 1275856879-1275877358
}
} else {//bytes=1275856879-1275877358
Rangeswitch = 2;
String temp0 = rangebytes.substring (0,rangebytes.indexof ('-'));
String Temp2 = rangebytes.substring (Rangebytes.indexof ('-') + 1, rangebytes.length ());
Pastlength = Long.parselong (Temp0.trim ())//bytes=1275856879-1275877358, download starting from 1,275,856,879th byte
Tolength = Long.parselong (TEMP2);//bytes=1275856879-1275877358, to the end of the 1,275,877,358th byte
ContentLength = tolength-pastlength + 1;//The client requested a byte between 1275856879-1275877358
}
} else {//download from start
ContentLength = filelength;//Client requires full-text download
}

/**
* If Content-length is set, the client will automatically download multi-threaded. If you do not want to support multi-threading, do not set this parameter.
* The format of the response is:
* Content-length: [total file Size]-[Start byte of the downloaded file block of the client request]
* Servletactioncontext.getresponse (). SetHeader ("Content-length",
* New Long (File.length ()-P). toString ());
*/
Response.reset ();//tells the client to allow a breakpoint to continue multiple lines thread attached download, the format of the response is: accept-ranges:bytes
Response.setheader ("accept-ranges", "bytes");//If it is the first time, there is no continuation of the breakpoint, the state is the default of 200, no need to explicitly set; the format of the response is: http/1.1-OK
if (pastlength! = 0) {
Not downloaded from the very beginning,
The format of the response is:
content-range:bytes [The total size of the file block's start byte]-[file-The total size of the 1]/[file]
System.out.println ("----------------------------not download from the beginning! The server is about to start the breakpoint continues to pass ... ");
Switch (rangeswitch) {
Case 1: {//Request for bytes=27000-
String Contentrange = new StringBuffer ("bytes"). Append (New Long (pastlength). toString ()). Append ("-"). Append (New Long ( fileLength-1). ToString ()). Append ("/"). Append (new Long (Filelength). ToString ()). ToString ();
Response.setheader ("Content-range", Contentrange);
Break
}
Case 2: {//Request for bytes=27000-39000
String Contentrange = rangebytes + "/" + new Long (filelength). toString ();
Response.setheader ("Content-range", Contentrange);
Break
}
Default: {
Break
}
}
} else {
is from the beginning to download
System.out.println ("----------------------------is downloaded from the beginning! ");
}

try {
Response.AddHeader ("Content-disposition", "attachment; Filename=\ "" + downloadfile.getname () + "\" ");
Response.setcontenttype (Commonutil.setcontenttype (Downloadfile.getname ()));//Set the MIME type.
Response.AddHeader ("Content-length", String.valueof (ContentLength));
OS = Response.getoutputstream ();
out = new Bufferedoutputstream (OS);
RAF = new Randomaccessfile (DownloadFile, "R");
try {
Switch (rangeswitch) {
Case 0: {//normal download, or download from the beginning
Same 1
}
Case 1: {//Request for bytes=27000-
Raf.seek (pastlength);//A client request that is shaped like bytes=969998336-, skipping 969,998,336 bytes
int n = 0;
while ((n = raf.read (b, 0, 1024))! =-1) {
Out.write (b, 0, N);
}
Break
}
Case 2: {//Request for bytes=27000-39000
Raf.seek (pastLength-1);//A client request that is shaped like bytes=1275856879-1275877358, finds the 1,275,856,879th byte
int n = 0;
Long readlength = 0;//The number of read bytes recorded
while (Readlength <= contentLength-1024) {///most bytes read here
n = raf.read (b, 0, 1024);
Readlength + = 1024;
Out.write (b, 0, N);
}
if (readlength <= contentlength) {//The remaining less than 1024 bytes are read here
n = raf.read (b, 0, (int) (contentlength-readlength));
Out.write (b, 0, N);
}
//
Raf.seek (pastlength);//A client request that is shaped like bytes=1275856879-1275877358, finds the 1,275,856,879th byte
while (Raf.getfilepointer () < Tolength) {
Out.write (Raf.read ());
// }
Break
}
Default: {
Break
}
}
Out.flush ();
} catch (IOException IE) {
/**
* At the time of writing the data,
* For exceptions such as Clientabortexception,
* Because the client canceled the download, and the server continues to write data to the browser,
* Throw this exception, this is normal.
* Especially for thunder this blood-sucking client software,
* Obviously there is a thread reading the bytes=1275856879-1275877358,
* If not read in a short time, the Thunderbolt will restart the second, the third ... Threads to read the same byte segments,
* Until one thread has finished reading, the Thunderbolt will kill other threads that are downloading the same byte segment,
* Forcibly abort byte readout, causing the server to throw clientabortexception.
* So, we ignore this exception
*/
Ignore
}
} catch (Exception e) {
System.err.println (e);
} finally {
if (out! = null) {
try {
Out.close ();
} catch (IOException e) {
System.err.println (e);
}
}
if (RAF! = NULL) {
try {
Raf.close ();
} catch (IOException e) {
System.err.println (e);
}
}
}
}
}

Package Com.defonds.cds.common;
public class Commonutil {

public static string setContentType (String returnfilename) {
String ContentType = "Application/octet-stream";
if (Returnfilename.lastindexof (".") < 0)
return contentType;
Returnfilename = Returnfilename.tolowercase ();
Returnfilename = returnfilename.substring (returnfilename
. LastIndexOf (".") + 1);

if (returnfilename.equals ("html") | | | returnfilename.equals ("htm")
|| Returnfilename.equals ("shtml")) {
ContentType = "text/html";
} else if (Returnfilename.equals ("CSS")) {
ContentType = "Text/css";
} else if (returnfilename.equals ("xml")) {
ContentType = "Text/xml";
} else if (Returnfilename.equals ("gif")) {
ContentType = "Image/gif";
} else if (Returnfilename.equals ("JPEG")
|| Returnfilename.equals ("jpg")) {
ContentType = "Image/jpeg";
} else if (Returnfilename.equals ("JS")) {
ContentType = "Application/x-javascript";
} else if (Returnfilename.equals ("atom")) {
ContentType = "Application/atom+xml";
} else if (Returnfilename.equals ("RSS")) {
ContentType = "Application/rss+xml";
} else if (Returnfilename.equals ("MML")) {
ContentType = "Text/mathml";
} else if (returnfilename.equals ("TXT")) {
ContentType = "Text/plain";
} else if (Returnfilename.equals ("Jad")) {
ContentType = "Text/vnd.sun.j2me.app-descriptor";
} else if (Returnfilename.equals ("WML")) {
ContentType = "TEXT/VND.WAP.WML";
} else if (Returnfilename.equals ("HTC")) {
ContentType = "Text/x-component";
} else if (Returnfilename.equals ("png")) {
ContentType = "Image/png";
} else if (Returnfilename.equals ("TIF")
|| Returnfilename.equals ("TIFF")) {
ContentType = "Image/tiff";
} else if (Returnfilename.equals ("Wbmp")) {
ContentType = "Image/vnd.wap.wbmp";
} else if (Returnfilename.equals ("ico")) {
ContentType = "Image/x-icon";
} else if (Returnfilename.equals ("Jng")) {
ContentType = "Image/x-jng";
} else if (Returnfilename.equals ("BMP")) {
ContentType = "Image/x-ms-bmp";
} else if (Returnfilename.equals ("svg")) {
ContentType = "Image/svg+xml";
} else if (Returnfilename.equals ("Jar") | | | returnfilename.equals ("var")
|| Returnfilename.equals ("ear")) {
ContentType = "Application/java-archive";
} else if (Returnfilename.equals ("Doc")) {
ContentType = "Application/msword";
} else if (Returnfilename.equals ("PDF")) {
ContentType = "Application/pdf";
} else if (Returnfilename.equals ("RTF")) {
ContentType = "Application/rtf";
} else if (Returnfilename.equals ("xls")) {
ContentType = "application/vnd.ms-excel";
} else if (Returnfilename.equals ("ppt")) {
ContentType = "Application/vnd.ms-powerpoint";
} else if (Returnfilename.equals ("7z")) {
ContentType = "application/x-7z-compressed";
} else if (Returnfilename.equals ("rar")) {
ContentType = "application/x-rar-compressed";
} else if (Returnfilename.equals ("swf")) {
ContentType = "Application/x-shockwave-flash";
} else if (Returnfilename.equals ("RPM")) {
ContentType = "Application/x-redhat-package-manager";
} else if (Returnfilename.equals ("der") | | | returnfilename.equals ("PEM")
|| Returnfilename.equals ("CRT")) {
ContentType = "Application/x-x509-ca-cert";
} else if (Returnfilename.equals ("xhtml")) {
ContentType = "Application/xhtml+xml";
} else if (Returnfilename.equals ("Zip")) {
ContentType = "Application/zip";
} else if (Returnfilename.equals ("mid")
|| Returnfilename.equals ("MIDI")
|| Returnfilename.equals ("Kar")) {
ContentType = "Audio/midi";
} else if (Returnfilename.equals ("MP3")) {
ContentType = "Audio/mpeg";
} else if (Returnfilename.equals ("Ogg")) {
ContentType = "Audio/ogg";
} else if (Returnfilename.equals ("M4A")) {
ContentType = "AUDIO/X-M4A";
} else if (Returnfilename.equals ("RA")) {
ContentType = "Audio/x-realaudio";
} else if (Returnfilename.equals ("3GPP")
|| Returnfilename.equals ("3gp")) {
ContentType = "VIDEO/3GPP";
} else if (Returnfilename.equals ("mp4")) {
ContentType = "Video/mp4";
} else if (Returnfilename.equals ("MPEG")
|| Returnfilename.equals ("mpg")) {
ContentType = "Video/mpeg";
} else if (Returnfilename.equals ("mov")) {
ContentType = "Video/quicktime";
} else if (Returnfilename.equals ("flv")) {
ContentType = "video/x-flv";
} else if (Returnfilename.equals ("M4V")) {
ContentType = "VIDEO/X-M4V";
} else if (Returnfilename.equals ("MNG")) {
ContentType = "VIDEO/X-MNG";
} else if (Returnfilename.equals ("ASX") | | | returnfilename.equals ("ASF")) {
ContentType = "VIDEO/X-MS-ASF";
} else if (Returnfilename.equals ("wmv")) {
ContentType = "video/x-ms-wmv";
} else if (Returnfilename.equals ("avi")) {
ContentType = "Video/x-msvideo";
}

return contentType;
}
}

HTTP breakpoint download Client and server

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.