Upload/download/UrlConnection/URL

文件上傳的核心點

1:用<input type=」file」/> 來聲明一個文件域。File:_____ <瀏覽>.javascript

2:必需要使用post方式的表單。html

3:必須設置表單的類型爲multipart/form-data.是設置這個表單傳遞的不是key=value值。傳遞的是字節碼.java

clip_image002

對於一個普通的表單來講只要它是post類型。默認就是算法

Content-type:application/x-www-from-urlencodedapache

表現形式瀏覽器

1:在request的請求頭中出現。緩存

2:在form聲明時設置一個類型enctype="application/x-www-form-urlencoded";服務器

若是要實現文件上傳,必須設置enctype=「multipart/form-data」--設置表單類型app

表單與請求的對應關係:框架

clip_image002[8]

如何獲取上傳的文件的內容-如下是本身手工解析txt文檔

package cn.itcast.servlet;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 若是一個表單的類型是post且enctype爲multipart/form-date
 * 則全部數據都是以二進制的方式向服務器上傳遞。
 * 因此req.getParameter("xxx")永遠爲null。
 * 只能夠經過req.getInputStream()來獲取數據,獲取正文的數據
 * 
 * @author wangjianme
 *
 */
public class UpServlet extends HttpServlet {
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String txt = req.getParameter("txt");//返回的是null
        System.err.println("txt is :"+txt);
        System.err.println("=========================================");
        InputStream in = req.getInputStream();
//        byte[] b= new byte[1024];
//        int len = 0;
//        while((len=in.read(b))!=-1){
//            String s = new String(b,0,len);
//            System.err.print(s);
//        }
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String firstLine = br.readLine();//讀取第一行,且第一行是分隔符號
        String fileName = br.readLine();
        fileName = fileName.substring(fileName.lastIndexOf("\\")+1);// bafasd.txt"
        fileName = fileName.substring(0,fileName.length()-1);
        
        br.readLine();
        br.readLine();
        String data = null;
        //獲取當前項目的運行路徑
        String projectPath = getServletContext().getRealPath("/up");
        PrintWriter out  = new PrintWriter(projectPath+"/"+fileName);
        while((data=br.readLine())!=null){
            if(data.equals(firstLine+"--")){
                break;
            }
            out.println(data);
        }
        out.close();
    }
}

使用apache-fileupload處理文件上傳<重點>

框架:是指將用戶常常處理的業務進行一個代碼封裝。讓用戶能夠方便的調用。

目前文件上傳的(框架)組件:

Apache----fileupload -

Orialiy – COS – 2008() -

Jsp-smart-upload – 200M。

用fileupload上傳文件:

須要導入第三方包:

Apache-fileupload.jar – 文件上傳核心包。

Apache-commons-io.jar – 這個包是fileupload的依賴包。同時又是一個工具包。

核心類:

DiskFileItemFactory – 設置磁盤空間,保存臨時文件。只是一個具類。

ServletFileUpload - 文件上傳的核心類,此類接收request,並解析reqeust。

servletfileUpload.parseRequest(requdest) - List<FileItem>

一個FileItem就是一個標識的開始:---------243243242342 到 ------------------245243523452—就是一個FileItem

第一步:導入包

第二步:書寫一個servlet完成doPost方法

/**
 * DiskFileItemFactory構造的兩個參數
 *     第一個參數:sizeThreadHold - 設置緩存(內存)保存多少字節數據,默認爲10K
 *                若是一個文件沒有大於10K,則直接使用內存直接保存成文件就能夠了。
 *              若是一個文件大於10K,就須要將文件先保存到臨時目錄中去。
 * 第二個參數 File 是指臨時目錄位置
 *
 */
public class Up2Servlet extends HttpServlet {
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setCharacterEncoding("UTf-8");
        //獲取項目的路徑
        String path = getServletContext().getRealPath("/up");
        //第一步聲明diskfileitemfactory工廠類,用於在指的磁盤上設置一個臨時目錄
        DiskFileItemFactory disk = 
                new DiskFileItemFactory(1024*10,new File("d:/a"));
        //第二步:聲明ServletFileUpoload,接收上面的臨時目錄
        ServletFileUpload up = new ServletFileUpload(disk);
        //第三步:解析request
        try {
            List<FileItem> list =  up.parseRequest(req);
            //若是就一個文件
            FileItem file = list.get(0);
            //獲取文件名,帶路徑
            String fileName = file.getName();
            fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
            //獲取文件的類型
            String fileType = file.getContentType();
            //獲取文件的字節碼
            InputStream in = file.getInputStream();
            //聲明輸出字節流
            OutputStream out = new FileOutputStream(path+"/"+fileName);
            //文件copy
            byte[] b = new byte[1024];
            int len = 0;
            while((len=in.read(b))!=-1){
                out.write(b,0,len);
            }
            out.close();
            
            long size = file.getInputStream().available();
            
            //刪除上傳的臨時文件
            file.delete();
            //顯示數據
            resp.setContentType("text/html;charset=UTf-8");
            PrintWriter op = resp.getWriter();
            op.print("文件上傳成功<br/>文件名:"+fileName);
            op.print("<br/>文件類型:"+fileType);
            op.print("<br/>文件大小(bytes)"+size);
            
            
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }

}

上傳多個文件

第一步:修改頁面的表單爲多個input type=」file」

<form action="<c:url value='/Up3Servlet'/>" method="post" enctype="multipart/form-data">
        File1:<input type="file" name="txt"><br/>
        File2:<input type="file" name="txt"><br/>
        <input type="submit"/>
    </form>

第二步:遍歷list<fileitem>

public class Up3Servlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String path = getServletContext().getRealPath("/up");
        //聲明disk
        DiskFileItemFactory disk = new DiskFileItemFactory();
        disk.setSizeThreshold(1024*1024);
        disk.setRepository(new File("d:/a"));
        //聲明解析requst的servlet
        ServletFileUpload up = new ServletFileUpload(disk);
        try{
            //解析requst
            List<FileItem> list = up.parseRequest(request);
            //聲明一個list<map>封裝上傳的文件的數據
            List<Map<String,String>> ups = new ArrayList<Map<String,String>>();
            for(FileItem file:list){
                Map<String,String> mm = new HashMap<String, String>();
                //獲取文件名
                String fileName = file.getName();
                fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
                String fileType = file.getContentType();
                InputStream in = file.getInputStream();
                int size = in.available();
                //使用工具類
                FileUtils.copyInputStreamToFile(in,new File(path+"/"+fileName));
                mm.put("fileName",fileName);
                mm.put("fileType",fileType);
                mm.put("size",""+size);
                
                ups.add(mm);
                file.delete();
            }
            request.setAttribute("ups",ups);
            //轉發
            request.getRequestDispatcher("/jsps/show.jsp").forward(request, response);
            
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

動態上傳多個文件

核心問題:在頁面上應該能夠控制<input type=」file」/>多少。

第一步:用table的格式化

<form name="xx" action="<c:url value='/Up3Servlet'/>" method="post" enctype="multipart/form-data">
    <table id="tb" border="1">
        <tr>
            <td>
                File:
            </td>
            <td>
                <input type="file" name="file">
                <button onclick="_del(this);">刪除</button>
            </td>
        </tr>
    </table>
    <br/>
    <input type="button" onclick="_submit();" value="上傳">
    <input onclick="_add();" type="button" value="增長">
    </form>
  </body>
  <script type="text/javascript">
      function _add(){
          var tb = document.getElementById("tb");
          //寫入一行
          var tr = tb.insertRow();
          //寫入列
          var td = tr.insertCell();
          //寫入數據
          td.innerHTML="File:";
          //再聲明一個新的td
          var td2 = tr.insertCell();
          //寫入一個input
          td2.innerHTML='<input type="file" name="file"/><button onclick="_del(this);">刪除</button>';
      }
      function _del(btn){
          var tr = btn.parentNode.parentNode;
          //alert(tr.tagName);
          //獲取tr在table中的下標
          var index = tr.rowIndex;
          //刪除
          var tb = document.getElementById("tb");
          tb.deleteRow(index);
      }
      function _submit(){
          //遍歷所的有文件
          var files = document.getElementsByName("file");
          if(files.length==0){
              alert("沒有能夠上傳的文件");
              return false;
          }
          for(var i=0;i<files.length;i++){
              if(files[i].value==""){
                  alert(""+(i+1)+"個文件不能爲空");
                  return false;
              }
          }
        document.forms['xx'].submit();
      }
  </script>
</html>

解決文件的重名的問題

package cn.itcast.servlet;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;

public class UpImgServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String path = getServletContext().getRealPath("/up");
        DiskFileItemFactory disk = 
                new DiskFileItemFactory(1024*10,new File("d:/a"));
        ServletFileUpload up = new ServletFileUpload(disk);
        try{
            List<FileItem> list = up.parseRequest(request);
            //只接收圖片*.jpg-iamge/jpege.,bmp/imge/bmp,png,
            List<String> imgs = new ArrayList<String>();
            for(FileItem file :list){
                if(file.getContentType().contains("image/")){
                    String fileName = file.getName();
                    fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
                    
                    //獲取擴展
                    String extName = fileName.substring(fileName.lastIndexOf("."));//.jpg
                    //UUID
                    String uuid = UUID.randomUUID().toString().replace("-", "");
                    //新名稱
                    String newName = uuid+extName;
                    
                    
                    FileUtils.copyInputStreamToFile(file.getInputStream(),
                            new File(path+"/"+newName));
                    //放到list
                    imgs.add(newName);
                }
                file.delete();
            }
            request.setAttribute("imgs",imgs);
            request.getRequestDispatcher("/jsps/imgs.jsp").forward(request, response);
        }catch(Exception e){
            e.printStackTrace();
        }
    
    }

}

處理帶說明信息的圖片

void

delete()
          刪除保存在臨時目錄中的文件。

String

getContentType()  獲取文檔的類型
          Returns the content type passed by the browser or null if not defined.

String

getFieldName() 獲取字段的名稱,即name=xxxx
          Returns the name of the field in the multipart form corresponding to this file item.

<input type=」file」 name=」img」/>

InputStream

getInputStream()
          Returns an InputStream that can be used to retrieve the contents of the file.

String

getName()
          Returns the original filename in the client's filesystem, as provided by the browser (or other client software).

獲取文件名稱。
若是是在IE獲取的文件爲 c:\aaa\aaa\xxx.jpg –即完整的路徑。
非IE;文件名稱只是 xxx.jpg

long

getSize()  獲取文件大小 至關於in.avilivable();
          Returns the size of the file item

 

若是你上傳是一普通的文本元素,則能夠經過如下方式獲取元素中的數據

<form enctype=」multipart/form-data」>

<input type=」text」 name=」name」/>

String

 

getString()  用於獲取普通的表單域的信息。
          Returns the contents of the file item as a String, using the default character encoding.(IOS-8859-1)

String

getString(String encoding) 能夠指定編碼格式
          Returns the contents of the file item as a String, using the specified encoding.

void

write(File file) 直接將文件保存到另外一個文件中去。
          A convenience method to write an uploaded item to disk.

  如下文件用判斷一個fileItem是不是file(type=file)對象或是text(type=text|checkbox|radio)對象:
boolean

isFormField()  若是是text|checkbox|radio|select這個值就是true.
          Determines whether or not a FileItem instance represents a simple form field.

示例代碼:

public class UpDescServlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");//能夠獲取中文的文件名
        String path = getServletContext().getRealPath("/up");
        DiskFileItemFactory disk = 
                new DiskFileItemFactory();
        disk.setRepository(new File("d:/a"));
        try{
            ServletFileUpload up = 
                    new ServletFileUpload(disk);
            List<FileItem> list = up.parseRequest(request);
            for(FileItem file:list){
                //第一步:判斷是不是普通的表單項
                if(file.isFormField()){
                    String fileName = file.getFieldName();//<input type="text" name="desc">=desc
                    String value = file.getString("UTF-8");//默認以ISO方式讀取數據
                    System.err.println(fileName+"="+value);
                }else{//說明是一個文件
                    String fileName = file.getName();
                    fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
                    file.write(new File(path+"/"+fileName));
                    System.err.println("文件名是:"+fileName);
                    System.err.println("文件大小是:"+file.getSize());
                    file.delete();
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

}

目錄打散-hash算法

會根據文件名計算一個目錄出來,計算的這個目錄必須是可再計算的。

原文件名爲:你的相片.jpg

修更名稱:8383902829432oiwowf.jpg

根據這個新的名稱字符串,獲取這個字符串的hash值 int hash = newName.hashCode();

hashCode =」」+ 898987878;

獲取後兩位做爲一個目錄:78.

目錄的個數:up/00-99/00-99 共100個目錄

package cn.itcast.servlet;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
 * 處理目錄打散。
 * 思想:對新生成的文件名進行二進制運算。
 * 先取後一位 int x = hashcode & 0xf;
 * 再取後第二位:int y = (hashCode >> 4) & 0xf;
 * @author wangjianme
 *
 */
public class DirServlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String path = getServletContext().getRealPath("/up");
        DiskFileItemFactory disk = 
                new DiskFileItemFactory();
        disk.setRepository(new File("d:/a"));
        try{
            ServletFileUpload up = new ServletFileUpload(disk);
            List<FileItem> list = up.parseRequest(request);
            for(FileItem file:list){
                if(!file.isFormField()){
                    String fileName = file.getName();
                    fileName=fileName.substring(fileName.lastIndexOf("\\")+1);
                    String extName = fileName.substring(fileName.lastIndexOf("."));
                    String newName = UUID.randomUUID().toString().replace("-","")+extName;
                    //第一步:獲取新名稱的hashcode
                    int code = newName.hashCode();
                    //第二步:獲取後一位作爲第一層目錄
                    String dir1 = 
                            Integer.toHexString(code & 0xf);
                    //獲取第二層的目錄
                    String dir2 = 
                            Integer.toHexString((code>>4)&0xf);
                    String savePath = dir1+"/"+dir2;
                    //組成保存的目錄
                    savePath=path+"/"+savePath;
                    //判斷目錄是否存在
                    File f = new File(savePath);
                    if(!f.exists()){
                        //建立目錄
                        f.mkdirs();
                    }
                    //保存文件
                    file.write(new File(savePath+"/"+newName));
                    file.delete();
                    //帶路徑保存到request
                    request.setAttribute("fileName",dir1+"/"+dir2+"/"+newName);
                }
            }
            
            request.getRequestDispatcher("/jsps/show.jsp").forward(request, response);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

}

性能提高

核心點用FileItemIterator it= up.getItemIterator(request);處理文件上傳。

package cn.itcast.servlet;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.RequestContext;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;
import org.apache.commons.io.FileUtils;

public class FastServlet extends HttpServlet {

    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String path = getServletContext().getRealPath("/up");
        DiskFileItemFactory disk = 
                new DiskFileItemFactory();
        disk.setRepository(new File("d:/a"));
        try{
            ServletFileUpload up = new ServletFileUpload(disk);
            //如下是迭代器模式
            FileItemIterator it= up.getItemIterator(request);
            while(it.hasNext()){
                FileItemStream item =  it.next();
                String fileName = item.getName();
                fileName=fileName.substring(fileName.lastIndexOf("\\")+1);
                InputStream in = item.openStream();
                FileUtils.copyInputStreamToFile(in,new File(path+"/"+fileName));
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        
    }

}

限制上傳大小

1:限制總文件的大小 。 如 上傳10文件,設置最多總上傳大小爲100M。

void

setSizeMax(long sizeMax)
          Sets the maximum allowed size of a complete request, as opposed to setFileSizeMax(long).

104857600

153046512

2:設置第每個文件的大小 ,若是設置每 一個文件大小10M。

void

setFileSizeMax(long fileSizeMax)
          Sets the maximum allowed size of a single uploaded file, as opposed to getSizeMax().

用COS實現文件上傳

package cn.itcast;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
import com.oreilly.servlet.multipart.FileRenamePolicy;
/**
 * 在Cos中就一個類,
 * MultipartRequest它是request的包裝類。
 */
public class CosServlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse resp)
            throws ServletException, IOException {
        //第一步:聲明文件的保存目錄
        String path = getServletContext().getRealPath("/up");
        //第二步:文件傳
        //聲明文件從新取名的策略
        FileRenamePolicy rename = new DefaultFileRenamePolicy();
        MultipartRequest req = 
                new MultipartRequest(request,path,1024*1024*100,"UTF-8",new MyRename());
        
//        //第三步:顯示信息,
        resp.setContentType("text/html;charset=UTf-8");
        PrintWriter out = resp.getWriter();
        
        out.print("文件名稱1:"+req.getOriginalFileName("img1"));
        out.print("<br/>新名稱:"+req.getFilesystemName("img1"));
        out.print("<br/>類型1:"+req.getContentType("img1"));
        out.print("<br/>大小1:"+req.getFile("img1").length());
        out.print("<br/>說明:"+req.getParameter("desc1"));
        if(req.getContentType("img1").contains("image/")){
            out.print("<img src='"+request.getContextPath()+"/up/"+req.getFilesystemName("img1")+"'></img>");
        }
        
//        out.print("<hr/>");
//        out.print("文件名稱2:"+req.getOriginalFileName("img2"));
//        out.print("<br/>類型2:"+req.getContentType("img2"));
//        out.print("<br/>大小2:"+req.getFile("img2").length());
//        out.print("<br/>說明2:"+req.getParameter("desc2"));
//        
//        
//        out.print("<hr/>");
//        out.print("文件名稱3:"+req.getOriginalFileName("img3"));
//        out.print("<br/>類型3:"+req.getContentType("img3"));
//        out.print("<br/>大小3:"+req.getFile("img3").length());
//        out.print("<br/>說明3:"+req.getParameter("desc3"));
    }
}
class MyRename implements FileRenamePolicy{
    public File rename(File file) {
        String fileName = file.getName();
        String extName = fileName.substring(fileName.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString().replace("-","");
        String newName = uuid+extName;//abc.jpg
        file = new File(file.getParent(),newName);
        return file;
    }
    
}

下載

便可以是get也能夠是post。

public void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String name = req.getParameter("name");
        //第一步:設置響應的類型
        resp.setContentType("application/force-download");
        //第二讀取文件
        String path = getServletContext().getRealPath("/up/"+name);
        InputStream in = new FileInputStream(path);
        //設置響應頭
        //對文件名進行url編碼
        name = URLEncoder.encode(name, "UTF-8");
        resp.setHeader("Content-Disposition","attachment;filename="+name);
        resp.setContentLength(in.available());
        
        //第三步:開始文件copy
        OutputStream out = resp.getOutputStream();
        byte[] b = new byte[1024];
        int len = 0;
        while((len=in.read(b))!=-1){
            out.write(b,0,len);
        }
        out.close();
        in.close();
    }

單線程斷點下載

服務使用斷點下載時,響應的信息是206。

UrlConnection - HttpurlConnection。-經過URL來獲取urlconnection實例。

第一步:正常下載

package cn.demo;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
public class CommonDown {
    public static void main(String[] args) throws Exception {
        String path = "http://localhost:6666/day22_cos/up/video.avi";
        URL url = new URL(path);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setDoInput(true);
        con.connect();
        int code = con.getResponseCode();
        System.err.println(code);
        if (code == 200) {
            //獲取文件大小
            long size = con.getContentLength();
            System.err.println("總大小是:"+size);
            //聲明下載到的字節
            long sum=0;
            BigDecimal bd = new BigDecimal(0D);
            double already = 0D;
            InputStream in = con.getInputStream();
            byte[] b = new byte[1024];
            int len = -1;
            OutputStream out = new FileOutputStream("d:/a/video.avi");
            while ((len = in.read(b)) != -1) {
                out.write(b, 0, len);
                sum=sum+len;
                double percent = ((double)sum)/((double)size);
                percent*=100;
                bd = new BigDecimal(percent);
                bd = bd.divide(new BigDecimal(1),0,BigDecimal.ROUND_HALF_UP);
                if(bd.doubleValue()!=already){
                    System.err.println(bd.intValue()+"%");
                    already=bd.doubleValue();
                }
            }
            out.close();
        }
    }
}

第二步:斷點下載

1:如何通知服務器只給我3之後數據。

req.setHeader("range","bytes=0-"); 從第0字節之後的全部字節

range=」bytes=3-」

2:我如何知道本身已經下載的3K數據。

讀取文件大小。

file.length();

3:若是從當前已經下載的文件後面開始追加數據。

FileRandomAccess 隨機訪問文件對象

seek(long);

skip(long);

URLConnection

此類用於在java代碼中模擬瀏覽器組成http協議向服務發請求(get/post)。

package cn.itcast;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class OneServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse resp)
            throws ServletException, IOException {
        String name = request.getParameter("name");
        System.err.println("這是get、、、、"+name);
        resp.setContentType("text/html;charset=UTF-8");
        resp.getWriter().print("你好:"+name);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse resp)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String name = request.getParameter("name");
        System.err.println("這是post請求......."+name);
        resp.setContentType("text/html;charset=UTF-8");
        resp.getWriter().print("你好:"+name);
    }

}

用urlconnection訪問oneSerlvet

package cn.demo;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.junit.Test;
public class Demo {
    /**
     * 發送get請求
     * @throws Exception
     */
    @Test
    public void testConn() throws Exception{
        //第一步:聲明url
        String urlPath = "http://localhost:6666/day22_cos/OneServlet?name=Jack";
        //第二步:聲明URL對象
        URL url = new URL(urlPath);
        //第三步:從url上獲取鏈接
        HttpURLConnection con=  (HttpURLConnection) url.openConnection();
        //第四步:設置訪問的類型
        con.setRequestMethod("GET");
        //第五步:設置能夠向服務器發信息。也能夠從服務器接收信息
        con.setDoInput(true); //也能夠從服務器接收信息
        con.setDoOutput(true); //設置能夠向服務器發信息
        //第六步:鏈接
        con.connect();
        //7:檢查鏈接狀態
        int code = con.getResponseCode();
        if(code==200){
            //8:從服務器讀取數據
            InputStream in = con.getInputStream();
            byte[] b = new byte[1024];
            int len = 0;
            while((len=in.read(b))!=-1){
                String s = new String(b,0,len,"UTF-8");
                System.err.print(s);
            }
        }
        //9:斷開
        con.disconnect();
    }
    /**
     * 如下發送post請求
     */
    @Test
    public void post() throws Exception{
        //第一步:聲明url
        String urlPath = "http://localhost:6666/day22_cos/OneServlet";
        //第二步:聲明URL對象
        URL url = new URL(urlPath);
        //第三步:從url上獲取鏈接
        HttpURLConnection con=  (HttpURLConnection) url.openConnection();
        //第四步:設置訪問的類型
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        //第五步:設置能夠向服務器發信息。也能夠從服務器接收信息
        con.setDoInput(true);//設置能夠向服務器發信息
        con.setDoOutput(true);//也能夠從服務器接收信息
        //第六步:發信息
        //獲取輸出流
        OutputStream out = con.getOutputStream();
        out.write("name=張三".getBytes("UTF-8"));
        
        
        //7:檢查鏈接狀態
        int code = con.getResponseCode();
        if(code==200){
            //8:從服務器讀取數據
            InputStream in = con.getInputStream();
            byte[] b = new byte[1024];
            int len = 0;
            while((len=in.read(b))!=-1){
                String s = new String(b,0,len,"UTF-8");
                System.err.print(s);
            }
        }
        //9:斷開
        con.disconnect();
    }
}
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息