1. 程式人生 > >Java利用HttpURLConnection傳送post請求上傳檔案

Java利用HttpURLConnection傳送post請求上傳檔案

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

  1.先寫個servlet把接收到的 HTTP 資訊儲存在一個檔案中, 看一下 form 表單到底封裝了什麼樣的資訊。

  Java程式碼

  public void doPost(HttpServletRequest request, HttpServletResponse response)

  throws ServletException, IOException {

  //獲取輸入流,是HTTP協議中的實體內容

  ServletInputStream  in=request.getInputStream();

  //緩衝區

  byte buffer[]=new byte[1024];

  FileOutputStream out=new FileOutputStream("d:\\test.log");

  int len=sis.read(buffer, 0, 1024);

  //把流裡的資訊迴圈讀入到file.log檔案中

  while( len!=-1 ){

  out.write(buffer, 0, len);

  len=in.readLine(buffer, 0, 1024);

  }

  out.close();

  in.close();

  }

  來一個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裡如下

  -----------------------------7da2e536604c8

  Content-Disposition: form-data; name="username"

  hello word

  -----------------------------7da2e536604c8

  Content-Disposition: form-data; name="file1"; filename="D:\haha.txt"

  Content-Type: text/plain

  haha

  hahaha

  -----------------------------7da2e536604c8

  Content-Disposition: form-data; name="file2"; filename="D:\huhu.txt"

  Content-Type: text/plain

  messi

  huhu

  -----------------------------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程式碼 public void upload(){

  List<String> list  = new ArrayList<String>();  //要上傳的檔名,如:d:\haha.doc.你要實現自己的業務。我這裡就是一個空list.

  try {

  String BOUNDARY = "---------7d4a6d158c9"; // 定義資料分隔線

  HttpURLConnection conn = (HttpURLConnection) url.openConnection();

  // 傳送POST請求必須設定如下兩行

  conn.setDoOutput(true);

  conn.setDoInput(true);

  conn.setUseCaches(false);

  conn.setRequestMethod("POST");

  conn.setRequestProperty("connection", "Keep-Alive");

  conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");

  conn.setRequestProperty("Charsert", "UTF-8");

  conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

  OutputStream out = new DataOutputStream(conn.getOutputStream());

  byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// 定義最後資料分隔線

  int leng = list.size();

  for(int i=0;i<leng;i++){

  String fname = list.get(i);

  File file = new File(fname);

  StringBuilder sb = new StringBuilder();

  sb.append("--");

  sb.append(BOUNDARY);

  sb.append("\r\n");

  sb.append("Content-Disposition: form-data;name=\"file"+i+"\";filename=\""+ file.getName() + "\"\r\n");

  sb.append("Content-Type:application/octet-stream\r\n\r\n");

  byte[] data = sb.toString().getBytes();

  out.write(data);

  DataInputStream in = new DataInputStream(new FileInputStream(file));

  int bytes = 0;

  byte[] bufferOut = new byte[1024];

  while ((bytes = in.read(bufferOut)) != -1) {

  out.write(bufferOut, 0, bytes);

  }

  out.write("\r\n".getBytes()); //多個檔案時,二個檔案之間加入這個

  in.close();

  }

  out.write(end_data);

  out.flush();

  out.close();

  // 定義BufferedReader輸入流來讀取URL的響應

  BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

  String line = null;

  while ((line = reader.readLine()) != null) {

  System.out.println(line);

  }

  } catch (Exception e) {

  System.out.println("傳送POST請求出現異常!" + e);

  e.printStackTrace();

  }

  }