利用HttpURLConnection發送post請求上傳文件

在頁面裏實現上傳文件不是什麼難事,寫個form,加上enctype = "multipart/form-data",在寫個接收的就可以了,沒什麼難的,如果要用java.net.HttpURLConnection來實現文件上傳,還真有點搞頭.:-)

1.先寫個servlet把接收到的 HTTP 信息保存在一個文件中, 看一下 form 表單到底封裝了什麼樣的信息。

Java代碼  收藏代碼
  1. public void doPost(HttpServletRequest request, HttpServletResponse response)  
  2.            throws ServletException, IOException {  
  3.        //獲取輸入流,是HTTP協議中的實體內容  
  4.        ServletInputStream  in=request.getInputStream();  
  5.        //緩衝區  
  6.        byte buffer[]=new byte[1024];  
  7.        FileOutputStream out=new FileOutputStream("d:\\test.log");  
  8.        int len=sis.read(buffer, 01024);  
  9.        //把流裏的信息循環讀入到file.log文件中  
  10.        while( len!=-1 ){  
  11.            out.write(buffer, 0, len);  
  12.            len=in.readLine(buffer, 01024);  
  13.   
  14.        }  
  15.        out.close();  
  16.        in.close();  
  17.     }  

 來一個form表單。

  <form name="upform" action="upload.do" method="POST"
            enctype="multipart/form-data">
            參數<input type="text" name="username"/><br/>
            文件1<input type="file" name="file1"/><br/>
            文件2<input type="file" name="file2"/><br/>
            <input type="submit" value="Submit" />
            <br />
     </form>

假如我參數寫的內容是hello word,然後二個文件是二個簡單的txt文件,上傳後test.log裏如下

Java代碼  收藏代碼
  1. -----------------------------7da2e536604c8  
  2. Content-Disposition: form-data; name="username"  
  3.   
  4. hello word  
  5. -----------------------------7da2e536604c8  
  6. Content-Disposition: form-data; name="file1"; filename="D:\haha.txt"  
  7. Content-Type: text/plain  
  8.   
  9. haha  
  10.   hahaha  
  11. -----------------------------7da2e536604c8  
  12. Content-Disposition: form-data; name="file2"; filename="D:\huhu.txt"  
  13. Content-Type: text/plain  
  14.   
  15. messi   
  16. huhu  
  17. -----------------------------7da2e536604c8--  

 

 研究下規律發現有如下幾點特徵

1.第一行是“ -----------------------------7d92221b604bc ”作爲分隔符,然後是“ \r\n ” 回車換行符。 這個7d92221b604bc 分隔符瀏覽器是隨機生成的。

2.第二行是Content-Disposition: form-data; name="file2"; filename="D:\huhu.txt";name=對應input的name值,filename對應要上傳的文件名(包括路徑在內),

3.第三行如果是文件就有Content-Type: text/plain;這裏上傳的是txt文件所以是text/plain,如果上穿的是jpg圖片的話就是image/jpg了,可以自己試試看看。

然後就是回車換行符。

4.在下就是文件或參數的內容或值了。如:hello word。

5.最後一行是-----------------------------7da2e536604c8--,注意最後多了二個--;

 

有了這些就可以使用HttpURLConnection來實現上傳文件功能了

Java代碼  收藏代碼
  1. public void upload(){  
  2.         List<String> list  = new ArrayList<String>();  //要上傳的文件名,如:d:\haha.doc.你要實現自己的業務。我這裏就是一個空list.  
  3.         try {  
  4.             String BOUNDARY = "---------7d4a6d158c9"// 定義數據分隔線  
  5.             URL url = new URL("http://localhost/JobPro/upload.do");  
  6.             HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  7.             // 發送POST請求必須設置如下兩行  
  8.             conn.setDoOutput(true);  
  9.             conn.setDoInput(true);  
  10.             conn.setUseCaches(false);  
  11.             conn.setRequestMethod("POST");  
  12.             conn.setRequestProperty("connection""Keep-Alive");  
  13.             conn.setRequestProperty("user-agent""Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");  
  14.             conn.setRequestProperty("Charsert""UTF-8");   
  15.             conn.setRequestProperty("Content-Type""multipart/form-data; boundary=" + BOUNDARY);  
  16.               
  17.             OutputStream out = new DataOutputStream(conn.getOutputStream());  
  18.             byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// 定義最後數據分隔線  
  19.             int leng = list.size();  
  20.             for(int i=0;i<leng;i++){  
  21.                 String fname = list.get(i);  
  22.                 File file = new File(fname);  
  23.                 StringBuilder sb = new StringBuilder();    
  24.                 sb.append("--");    
  25.                 sb.append(BOUNDARY);    
  26.                 sb.append("\r\n");    
  27.                 sb.append("Content-Disposition: form-data;name=\"file"+i+"\";filename=\""+ file.getName() + "\"\r\n");    
  28.                 sb.append("Content-Type:application/octet-stream\r\n\r\n");    
  29.                   
  30.                 byte[] data = sb.toString().getBytes();  
  31.                 out.write(data);  
  32.                 DataInputStream in = new DataInputStream(new FileInputStream(file));  
  33.                 int bytes = 0;  
  34.                 byte[] bufferOut = new byte[1024];  
  35.                 while ((bytes = in.read(bufferOut)) != -1) {  
  36.                     out.write(bufferOut, 0, bytes);  
  37.                 }  
  38.                 out.write("\r\n".getBytes()); //多個文件時,二個文件之間加入這個  
  39.                 in.close();  
  40.             }  
  41.             out.write(end_data);  
  42.             out.flush();    
  43.             out.close();   
  44.               
  45.             // 定義BufferedReader輸入流來讀取URL的響應  
  46.             BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));  
  47.             String line = null;  
  48.             while ((line = reader.readLine()) != null) {  
  49.                 System.out.println(line);  
  50.             }  
  51.   
  52.         } catch (Exception e) {  
  53.             System.out.println("發送POST請求出現異常!" + e);  
  54.             e.printStackTrace();  
  55.         }  
  56.     } 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章