91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么在JAVA中利用HttpURLConnection實現一個文件上傳下載功能

發布時間:2020-12-07 16:24:33 來源:億速云 閱讀:236 作者:Leah 欄目:編程語言

怎么在JAVA中利用HttpURLConnection實現一個文件上傳下載功能?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。

HttpURLConnection文件上傳

HttpURLConnection采用模擬瀏覽器上傳的數據格式,上傳給服務器

上傳代碼如下:

package com.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;

/**
 * Java原生的API可用于發送HTTP請求,即java.net.URL、java.net.URLConnection,這些API很好用、很常用,
 * 但不夠簡便;
 * 
 * 1.通過統一資源定位器(java.net.URL)獲取連接器(java.net.URLConnection) 2.設置請求的參數 3.發送請求
 * 4.以輸入流的形式獲取返回內容 5.關閉輸入流
 * 
 * @author H__D
 *
 */
public class HttpConnectionUtil {


 /**
  * 多文件上傳的方法
  * 
  * @param actionUrl:上傳的路徑
  * @param uploadFilePaths:需要上傳的文件路徑,數組
  * @return
  */
 @SuppressWarnings("finally")
 public static String uploadFile(String actionUrl, String[] uploadFilePaths) {
  String end = "\r\n";
  String twoHyphens = "--";
  String boundary = "*****";

  DataOutputStream ds = null;
  InputStream inputStream = null;
  InputStreamReader inputStreamReader = null;
  BufferedReader reader = null;
  StringBuffer resultBuffer = new StringBuffer();
  String tempLine = null;

  try {
   // 統一資源
   URL url = new URL(actionUrl);
   // 連接類的父類,抽象類
   URLConnection urlConnection = url.openConnection();
   // http的連接類
   HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;

   // 設置是否從httpUrlConnection讀入,默認情況下是true;
   httpURLConnection.setDoInput(true);
   // 設置是否向httpUrlConnection輸出
   httpURLConnection.setDoOutput(true);
   // Post 請求不能使用緩存
   httpURLConnection.setUseCaches(false);
   // 設定請求的方法,默認是GET
   httpURLConnection.setRequestMethod("POST");
   // 設置字符編碼連接參數
   httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
   // 設置字符編碼
   httpURLConnection.setRequestProperty("Charset", "UTF-8");
   // 設置請求內容類型
   httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

   // 設置DataOutputStream
   ds = new DataOutputStream(httpURLConnection.getOutputStream());
   for (int i = 0; i < uploadFilePaths.length; i++) {
    String uploadFile = uploadFilePaths[i];
    String filename = uploadFile.substring(uploadFile.lastIndexOf("//") + 1);
    ds.writeBytes(twoHyphens + boundary + end);
    ds.writeBytes("Content-Disposition: form-data; " + "name=\"file" + i + "\";filename=\"" + filename
      + "\"" + end);
    ds.writeBytes(end);
    FileInputStream fStream = new FileInputStream(uploadFile);
    int bufferSize = 1024;
    byte[] buffer = new byte[bufferSize];
    int length = -1;
    while ((length = fStream.read(buffer)) != -1) {
     ds.write(buffer, 0, length);
    }
    ds.writeBytes(end);
    /* close streams */
    fStream.close();
   }
   ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
   /* close streams */
   ds.flush();
   if (httpURLConnection.getResponseCode() >= 300) {
    throw new Exception(
      "HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
   }

   if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
    inputStream = httpURLConnection.getInputStream();
    inputStreamReader = new InputStreamReader(inputStream);
    reader = new BufferedReader(inputStreamReader);
    tempLine = null;
    resultBuffer = new StringBuffer();
    while ((tempLine = reader.readLine()) != null) {
     resultBuffer.append(tempLine);
     resultBuffer.append("\n");
    }
   }

  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } finally {
   if (ds != null) {
    try {
     ds.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
   if (reader != null) {
    try {
     reader.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
   if (inputStreamReader != null) {
    try {
     inputStreamReader.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
   if (inputStream != null) {
    try {
     inputStream.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }

   return resultBuffer.toString();
  }
 }


 public static void main(String[] args) {

  // 上傳文件測試
   String str = uploadFile("http://127.0.0.1:8080/image/image.do",new String[] { "/Users//H__D/Desktop//1.png","//Users/H__D/Desktop/2.png" });
   System.out.println(str);


 }

}

HttpURLConnection文件下載

下載代碼如下:

package com.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;

/**
 * Java原生的API可用于發送HTTP請求,即java.net.URL、java.net.URLConnection,這些API很好用、很常用,
 * 但不夠簡便;
 * 
 * 1.通過統一資源定位器(java.net.URL)獲取連接器(java.net.URLConnection) 2.設置請求的參數 3.發送請求
 * 4.以輸入流的形式獲取返回內容 5.關閉輸入流
 * 
 * @author H__D
 *
 */
public class HttpConnectionUtil {


 /**
  * 
  * @param urlPath
  *   下載路徑
  * @param downloadDir
  *   下載存放目錄
  * @return 返回下載文件
  */
 public static File downloadFile(String urlPath, String downloadDir) {
  File file = null;
  try {
   // 統一資源
   URL url = new URL(urlPath);
   // 連接類的父類,抽象類
   URLConnection urlConnection = url.openConnection();
   // http的連接類
   HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
   // 設定請求的方法,默認是GET
   httpURLConnection.setRequestMethod("POST");
   // 設置字符編碼
   httpURLConnection.setRequestProperty("Charset", "UTF-8");
   // 打開到此 URL 引用的資源的通信鏈接(如果尚未建立這樣的連接)。
   httpURLConnection.connect();

   // 文件大小
   int fileLength = httpURLConnection.getContentLength();

   // 文件名
   String filePathUrl = httpURLConnection.getURL().getFile();
   String fileFullName = filePathUrl.substring(filePathUrl.lastIndexOf(File.separatorChar) + 1);

   System.out.println("file length---->" + fileLength);

   URLConnection con = url.openConnection();

   BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());

   String path = downloadDir + File.separatorChar + fileFullName;
   file = new File(path);
   if (!file.getParentFile().exists()) {
    file.getParentFile().mkdirs();
   }
   OutputStream out = new FileOutputStream(file);
   int size = 0;
   int len = 0;
   byte[] buf = new byte[1024];
   while ((size = bin.read(buf)) != -1) {
    len += size;
    out.write(buf, 0, size);
    // 打印下載百分比
    // System.out.println("下載了-------> " + len * 100 / fileLength +
    // "%\n");
   }
   bin.close();
   out.close();
  } catch (MalformedURLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } finally {
   return file;
  }

 }

 public static void main(String[] args) {

  // 下載文件測試
  downloadFile("http://localhost:8080/images/1467523487190.png", "/Users/H__D/Desktop");

 }

}

看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

陆河县| 平泉县| 莎车县| 扎赉特旗| 文成县| 宜丰县| 屏南县| 临汾市| 巴中市| 濮阳市| 高碑店市| 凤翔县| 瑞安市| 永德县| 塔河县| 天柱县| 涞水县| 长治市| 乳山市| 南澳县| 德昌县| 武功县| 郁南县| 邓州市| 吉安市| 浮山县| 行唐县| 高陵县| 田林县| 上杭县| 肥乡县| 延安市| 团风县| 通河县| 和硕县| 潜江市| 应用必备| 长顺县| 康平县| 峨眉山市| 二连浩特市|