??xml version="1.0" encoding="utf-8" standalone="yes"?>
断点l传的原?/span>
其实断点l传的原理很单,是?Http 的请求上和一般的下蝲有所不同而已?
打个比方Q浏览器h服务器上的一个文Ӟ所发出的请求如下:(x)
假设服务器域名ؓ(f) wwww.sjtu.edu.cnQ文件名?down.zip?
GET /down.zip HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-
excel, application/msword, application/vnd.ms-powerpoint, */*
Accept-Language: zh-cn
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)
Connection: Keep-Alive
服务器收到请求后Q按要求Lh的文Ӟ提取文g的信息,然后q回l浏览器Q返回信息如下:(x)
200
Content-Length=106786028
Accept-Ranges=bytes
Date=Mon, 30 Apr 2001 12:56:11 GMT
ETag=W/"02ca57e173c11:95b"
Content-Type=application/octet-stream
Server=Microsoft-IIS/5.0
Last-Modified=Mon, 30 Apr 2001 12:56:11 GMT
所谓断点箋传,也就是要从文件已l下载的地方开始l下载。所以在客户端浏览器传给 Web 服务器的时候要多加一条信?-- 从哪里开始?
下面是用自己~的一?览?来传递请求信息给 Web 服务器,要求?2000070 字节开始?
GET /down.zip HTTP/1.0
User-Agent: NetFox
RANGE: bytes=2000070-
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
仔细看一下就?x)发现多了(jin)一?RANGE: bytes=2000070-
q一行的意思就是告诉服务器 down.zip q个文g?2000070 字节开始传Q前面的字节不用传了(jin)?
服务器收到这个请求以后,q回的信息如下:(x)
206
Content-Length=106786028
Content-Range=bytes 2000070-106786027/106786028
Date=Mon, 30 Apr 2001 12:55:20 GMT
ETag=W/"02ca57e173c11:95b"
Content-Type=application/octet-stream
Server=Microsoft-IIS/5.0
Last-Modified=Mon, 30 Apr 2001 12:55:20 GMT
和前面服务器q回的信息比较一下,׃(x)发现增加?jin)一行:(x)
Content-Range=bytes 2000070-106786027/106786028
q回的代码也改ؓ(f) 206 ?jin),而不再是 200 ?jin)?
知道?jin)以上原理,可以进行断点箋传的~程?jin)?
从输入流中取出的字节就?down.zip 文g?2000070 开始的字节。大家看Q其实断点箋传用 Java 实现hq是很简单的吧。接下来要做的事是怎么保存获得的流到文件中M(jin)?
怎么P也很单吧。接下来要做的就是整合成一个完整的E序?jin)。包括一pd的线E控制等{?
主要用了(jin) 6 个类Q包括一个测试类?
SiteFileFetch.java 负责整个文g的抓取,控制内部U程 (FileSplitterFetch c?)?
FileSplitterFetch.java 负责部分文g的抓取?
FileAccess.java 负责文g的存储?
SiteInfoBean.java 要抓取的文g的信息,如文件保存的目录Q名字,抓取文g?URL {?
Utility.java 工具c,放一些简单的Ҏ(gu)?
TestMethod.java 试cR?
下面是源E序Q?/p>
/* /* * SiteFileFetch.java */ package NetFox; import java.io.*; import java.net.*; public class SiteFileFetch extends Thread { SiteInfoBean siteInfoBean = null; // 文g信息 Bean long[] nStartPos; // 开始位|? long[] nEndPos; // l束位置 FileSplitterFetch[] fileSplitterFetch; // 子线E对? long nFileLength; // 文g长度 boolean bFirst = true; // 是否W一ơ取文g boolean bStop = false; // 停止标志 File tmpFile; // 文g下蝲的(f)时信? DataOutputStream output; // 输出到文件的输出? public SiteFileFetch(SiteInfoBean bean) throws IOException { siteInfoBean = bean; //tmpFile = File.createTempFile ("zhong","1111",new File(bean.getSFilePath())); tmpFile = new File(bean.getSFilePath()+File.separator + bean.getSFileName()+".info"); if(tmpFile.exists ()) { bFirst = false; read_nPos(); } else { nStartPos = new long[bean.getNSplitter()]; nEndPos = new long[bean.getNSplitter()]; } } public void run() { // 获得文g长度 // 分割文g // 实例 FileSplitterFetch // 启动 FileSplitterFetch U程 // {待子线E返? try{ if(bFirst) { nFileLength = getFileSize(); if(nFileLength == -1) { System.err.println("File Length is not known!"); } else if(nFileLength == -2) { System.err.println("File is not access!"); } else { for(int i=0;i<nStartPos.length;i++) { nStartPos[i] = (long)(i*(nFileLength/nStartPos.length)); } for(int i=0;i<nEndPos.length-1;i++) { nEndPos[i] = nStartPos[i+1]; } nEndPos[nEndPos.length-1] = nFileLength; } } // 启动子线E? fileSplitterFetch = new FileSplitterFetch[nStartPos.length]; for(int i=0;i<nStartPos.length;i++) { fileSplitterFetch[i] = new FileSplitterFetch(siteInfoBean.getSSiteURL(), siteInfoBean.getSFilePath() + File.separator + siteInfoBean.getSFileName(), nStartPos[i],nEndPos[i],i); Utility.log("Thread " + i + " , nStartPos = " + nStartPos[i] + ", nEndPos = " + nEndPos[i]); fileSplitterFetch[i].start(); } // fileSplitterFetch[nPos.length-1] = new FileSplitterFetch(siteInfoBean.getSSiteURL(), siteInfoBean.getSFilePath() + File.separator + siteInfoBean.getSFileName(),nPos[nPos.length-1],nFileLength,nPos.length-1); // Utility.log("Thread " +(nPos.length-1) + ",nStartPos = "+nPos[nPos.length-1]+", nEndPos = " + nFileLength); // fileSplitterFetch[nPos.length-1].start(); // {待子线E结? //int count = 0; // 是否l束 while 循环 boolean breakWhile = false; while(!bStop) { write_nPos(); Utility.sleep(500); breakWhile = true; for(int i=0;i<nStartPos.length;i++) { if(!fileSplitterFetch[i].bDownOver) { breakWhile = false; break; } } if(breakWhile) break; //count++; //if(count>4) // siteStop(); } System.err.println("文g下蝲l束Q?); } catch(Exception e){e.printStackTrace ();} } // 获得文g长度 public long getFileSize() { int nFileLength = -1; try{ URL url = new URL(siteInfoBean.getSSiteURL()); HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection (); httpConnection.setRequestProperty("User-Agent","NetFox"); int responseCode=httpConnection.getResponseCode(); if(responseCode>=400) { processErrorCode(responseCode); return -2; //-2 represent access is error } String sHeader; for(int i=1;;i++) { //DataInputStream in = new DataInputStream(httpConnection.getInputStream ()); //Utility.log(in.readLine()); sHeader=httpConnection.getHeaderFieldKey(i); if(sHeader!=null) { if(sHeader.equals("Content-Length")) { nFileLength = Integer.parseInt(httpConnection.getHeaderField(sHeader)); break; } } else break; } } catch(IOException e){e.printStackTrace ();} catch(Exception e){e.printStackTrace ();} Utility.log(nFileLength); return nFileLength; } // 保存下蝲信息Q文件指针位|)(j) private void write_nPos() { try{ output = new DataOutputStream(new FileOutputStream(tmpFile)); output.writeInt(nStartPos.length); for(int i=0;i<nStartPos.length;i++) { // output.writeLong(nPos[i]); output.writeLong(fileSplitterFetch[i].nStartPos); output.writeLong(fileSplitterFetch[i].nEndPos); } output.close(); } catch(IOException e){e.printStackTrace ();} catch(Exception e){e.printStackTrace ();} } // d保存的下载信息(文g指针位置Q? private void read_nPos() { try{ DataInputStream input = new DataInputStream(new FileInputStream(tmpFile)); int nCount = input.readInt(); nStartPos = new long[nCount]; nEndPos = new long[nCount]; for(int i=0;i<nStartPos.length;i++) { nStartPos[i] = input.readLong(); nEndPos[i] = input.readLong(); } input.close(); } catch(IOException e){e.printStackTrace ();} catch(Exception e){e.printStackTrace ();} } private void processErrorCode(int nErrorCode) { System.err.println("Error Code : " + nErrorCode); } // 停止文g下蝲 public void siteStop() { bStop = true; for(int i=0;i<nStartPos.length;i++) fileSplitterFetch[i].splitterStop(); } } |
/* **FileSplitterFetch.java */ package NetFox; import java.io.*; import java.net.*; public class FileSplitterFetch extends Thread { String sURL; //File URL long nStartPos; //File Snippet Start Position long nEndPos; //File Snippet End Position int nThreadID; //Thread's ID boolean bDownOver = false; //Downing is over boolean bStop = false; //Stop identical FileAccessI fileAccessI = null; //File Access interface public FileSplitterFetch(String sURL,String sName,long nStart,long nEnd,int id) throws IOException { this.sURL = sURL; this.nStartPos = nStart; this.nEndPos = nEnd; nThreadID = id; fileAccessI = new FileAccessI(sName,nStartPos); } public void run() { while(nStartPos < nEndPos && !bStop) { try{ URL url = new URL(sURL); HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection (); httpConnection.setRequestProperty("User-Agent","NetFox"); String sProperty = "bytes="+nStartPos+"-"; httpConnection.setRequestProperty("RANGE",sProperty); Utility.log(sProperty); InputStream input = httpConnection.getInputStream(); //logResponseHead(httpConnection); byte[] b = new byte[1024]; int nRead; while((nRead=input.read(b,0,1024)) > 0 && nStartPos < nEndPos && !bStop) { nStartPos += fileAccessI.write(b,0,nRead); //if(nThreadID == 1) // Utility.log("nStartPos = " + nStartPos + ", nEndPos = " + nEndPos); } Utility.log("Thread " + nThreadID + " is over!"); bDownOver = true; //nPos = fileAccessI.write (b,0,nRead); } catch(Exception e){e.printStackTrace ();} } } // 打印回应的头信息 public void logResponseHead(HttpURLConnection con) { for(int i=1;;i++) { String header=con.getHeaderFieldKey(i); if(header!=null) //responseHeaders.put(header,httpConnection.getHeaderField(header)); Utility.log(header+" : "+con.getHeaderField(header)); else break; } } public void splitterStop() { bStop = true; } } /* **FileAccess.java */ package NetFox; import java.io.*; public class FileAccessI implements Serializable{ RandomAccessFile oSavedFile; long nPos; public FileAccessI() throws IOException { this("",0); } public FileAccessI(String sName,long nPos) throws IOException { oSavedFile = new RandomAccessFile(sName,"rw"); this.nPos = nPos; oSavedFile.seek(nPos); } public synchronized int write(byte[] b,int nStart,int nLen) { int n = -1; try{ oSavedFile.write(b,nStart,nLen); n = nLen; } catch(IOException e) { e.printStackTrace (); } return n; } } /* **SiteInfoBean.java */ package NetFox; public class SiteInfoBean { private String sSiteURL; //Site's URL private String sFilePath; //Saved File's Path private String sFileName; //Saved File's Name private int nSplitter; //Count of Splited Downloading File public SiteInfoBean() { //default value of nSplitter is 5 this("","","",5); } public SiteInfoBean(String sURL,String sPath,String sName,int nSpiltter) { sSiteURL= sURL; sFilePath = sPath; sFileName = sName; this.nSplitter = nSpiltter; } public String getSSiteURL() { return sSiteURL; } public void setSSiteURL(String value) { sSiteURL = value; } public String getSFilePath() { return sFilePath; } public void setSFilePath(String value) { sFilePath = value; } public String getSFileName() { return sFileName; } public void setSFileName(String value) { sFileName = value; } public int getNSplitter() { return nSplitter; } public void setNSplitter(int nCount) { nSplitter = nCount; } } /* **Utility.java */ package NetFox; public class Utility { public Utility() { } public static void sleep(int nSecond) { try{ Thread.sleep(nSecond); } catch(Exception e) { e.printStackTrace (); } } public static void log(String sMsg) { System.err.println(sMsg); } public static void log(int sMsg) { System.err.println(sMsg); } } /* **TestMethod.java */ package NetFox; public class TestMethod { public TestMethod() { ///xx/weblogic60b2_win.exe try{ SiteInfoBean bean = new SiteInfoBean("http://localhost/xx/weblogic60b2_win.exe", "L:\\temp","weblogic60b2_win.exe",5); //SiteInfoBean bean = new SiteInfoBean("http://localhost:8080/down.zip","L:\\temp", "weblogic60b2_win.exe",5); SiteFileFetch fileFetch = new SiteFileFetch(bean); fileFetch.start(); } catch(Exception e){e.printStackTrace ();} } public static void main(String[] args) { new TestMethod(); } } |
<%@ page contentType="text/html; charset=GBK" %>
<% response.setContentType("application/vnd.ms-excel;charset=GBK");
response.setHeader("Content-disposition","attachment; filename=test2.xls");
%>
<!--以下Z持成html面的excel的内?demo.html面-->
<html xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns="http://www.w3.org/TR/REC-html40">
<head>
<meta http-equiv=Content-Type content="text/html; charset=gb2312">
<meta name=ProgId content=Excel.Sheet>
<meta name=Generator content="Microsoft Excel 11">
<link rel=File-List href="qwe.files/filelist.xml">
<link rel=Edit-Time-Data href="qwe.files/editdata.mso">
<link rel=OLE-Object-Data href="qwe.files/oledata.mso">
<!--[if gte mso 9]><xml>
<o:DocumentProperties>
<o:Created>1996-12-17T01:32:42Z</o:Created>
<o:LastSaved>2010-05-12T13:59:04Z</o:LastSaved>
<o:Version>11.9999</o:Version>
</o:DocumentProperties>
<o:OfficeDocumentSettings>
<o:RemovePersonalInformation/>
</o:OfficeDocumentSettings>
</xml><![endif]-->
<style>
<!--table
{mso-displayed-decimal-separator:"\.";
mso-displayed-thousand-separator:"\,";}
@page
{margin:1.0in .75in 1.0in .75in;
mso-header-margin:.5in;
mso-footer-margin:.5in;}
tr
{mso-height-source:auto;
mso-ruby-visibility:none;}
col
{mso-width-source:auto;
mso-ruby-visibility:none;}
br
{mso-data-placement:same-cell;}
.style0
{mso-number-format:General;
text-align:general;
vertical-align:bottom;
white-space:nowrap;
mso-rotate:0;
mso-background-source:auto;
mso-pattern:auto;
color:windowtext;
font-size:12.0pt;
font-weight:400;
font-style:normal;
text-decoration:none;
font-family:宋体;
mso-generic-font-family:auto;
mso-font-charset:134;
border:none;
mso-protection:locked visible;
mso-style-name:常规;
mso-style-id:0;}
td
{mso-style-parent:style0;
padding-top:1px;
padding-right:1px;
padding-left:1px;
mso-ignore:padding;
color:windowtext;
font-size:12.0pt;
font-weight:400;
font-style:normal;
text-decoration:none;
font-family:宋体;
mso-generic-font-family:auto;
mso-font-charset:134;
mso-number-format:General;
text-align:general;
vertical-align:bottom;
border:none;
mso-background-source:auto;
mso-pattern:auto;
mso-protection:locked visible;
white-space:nowrap;
mso-rotate:0;}
ruby
{ruby-align:left;}
rt
{color:windowtext;
font-size:9.0pt;
font-weight:400;
font-style:normal;
text-decoration:none;
font-family:宋体;
mso-generic-font-family:auto;
mso-font-charset:134;
mso-char-type:none;
display:none;}
-->
</style>
<!--[if gte mso 9]><xml>
<x:ExcelWorkbook>
<x:ExcelWorksheets>
<x:ExcelWorksheet>
<x:Name>Sheet1</x:Name>
<x:WorksheetOptions>
<x:DefaultRowHeight>285</x:DefaultRowHeight>
<x:CodeName>Sheet1</x:CodeName>
<x:Selected/>
<x:Panes>
<x:Pane>
<x:Number>3</x:Number>
<x:ActiveCol>1</x:ActiveCol>
</x:Pane>
</x:Panes>
<x:ProtectContents>False</x:ProtectContents>
<x:ProtectObjects>False</x:ProtectObjects>
<x:ProtectScenarios>False</x:ProtectScenarios>
</x:WorksheetOptions>
</x:ExcelWorksheet>
<x:ExcelWorksheet>
<x:Name>Sheet2</x:Name>
<x:WorksheetOptions>
<x:DefaultRowHeight>285</x:DefaultRowHeight>
<x:CodeName>Sheet2</x:CodeName>
<x:ProtectContents>False</x:ProtectContents>
<x:ProtectObjects>False</x:ProtectObjects>
<x:ProtectScenarios>False</x:ProtectScenarios>
</x:WorksheetOptions>
</x:ExcelWorksheet>
<x:ExcelWorksheet>
<x:Name>Sheet3</x:Name>
<x:WorksheetOptions>
<x:DefaultRowHeight>285</x:DefaultRowHeight>
<x:CodeName>Sheet3</x:CodeName>
<x:ProtectContents>False</x:ProtectContents>
<x:ProtectObjects>False</x:ProtectObjects>
<x:ProtectScenarios>False</x:ProtectScenarios>
</x:WorksheetOptions>
</x:ExcelWorksheet>
</x:ExcelWorksheets>
<x:WindowHeight>4530</x:WindowHeight>
<x:WindowWidth>8505</x:WindowWidth>
<x:WindowTopX>480</x:WindowTopX>
<x:WindowTopY>120</x:WindowTopY>
<x:AcceptLabelsInFormulas/>
<x:ProtectStructure>False</x:ProtectStructure>
<x:ProtectWindows>False</x:ProtectWindows>
</x:ExcelWorkbook>
</xml><![endif]-->
</head>
<body link=blue vlink=purple>
<table x:str border=0 cellpadding=0 cellspacing=0 width=288 style='border-collapse:
collapse;table-layout:fixed;width:216pt'>
<col width=72 span=4 style='width:54pt'>
<tr height=19 style='height:14.25pt'>
<td height=19 width=72 style='height:14.25pt;width:54pt'>全球</td>
<td width=72 style='width:54pt'>问问</td>
<td width=72 style='width:54pt'>ee</td>
<td width=72 style='width:54pt'>rr</td>
</tr>
<tr height=19 style='height:14.25pt'>
<td height=19 style='height:14.25pt'>暗暗</td>
<td>ss</td>
<td>dd</td>
<td>ff</td>
</tr>
<![if supportMisalignedColumns]>
<tr height=0 style='display:none'>
<td width=72 style='width:54pt'></td>
<td width=72 style='width:54pt'></td>
<td width=72 style='width:54pt'></td>
<td width=72 style='width:54pt'></td>
</tr>
<![endif]>
</table>
</body>
</html>
中文问题Q?br />
查看源代码时发现JSP文g中写ȝ中文Zؕ码,则在JSP文g头部d一?br />
<%@ page contentType="text/html; charset=gb2312" %>
查看源代码时发现文字Z文,但是用Excel打开Zؕ码则?lt;html>?lt;head>中加?br />
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
在jsp面中,要在excel中显C的内容可以从数据库中读取,在此׃做详l的介绍?/p>
我在web.xml中设|?lt;welcome-file>HnSp/index.html</welcome-file>,可是前台index.html
能显C出来,可是面中的囄都显CZ出来Qindex.html中的囄的\径都是用的相对\
径)(j)Q后来在发现昄的页面中的图片少?jin)一U,在图片的路径前加入HnSpp正确昄?/p>
Q可是在别的面通过链接讉Kindex.html面Q图片还是显CZ出来Q看?jin)知道,多?jin)?/p>
HnSpQ看来在囄的\径前加入HnSp是不对的Q?br /> 我一直想不懂Z么,后来想了(jin)个办法解决了(jin)Q就是在WebRoot下新Z个新的空面
MyJspjspQ写入如下代?<%response.sendRedirect("HnSp/index.html"); %>Q然后把
<welcome-file>HnSp/index.html</welcome-file>,改ؓ(f)<welcome-
file>MyJsp.jsp</welcome-file>,q样问题p决了(jin)Q都不存在\径错误问题了(jin)Q?/p>
response.sendRedirect()
是在用户的浏览器端工?sendRedirect()可以带参C?比如servlet?name=frank传至?/p>
个页?同时它可以重定向至不同的L?sendRedirect()可以重定向有frame.的jsp文g.
重定向后在浏览器地址栏上?x)出现重定向面的URLQ由于response是jsp面中的隐含对象
Q故在jsp面中可以用response.sendRedirect()直接实现重定位?br />