欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JAVA通過HttpURLConnection 上傳和下載文件的方法

 更新時間:2017年09月26日 10:13:30   作者:H__D  
這篇文章主要介紹了JAVA通過HttpURLConnection 上傳和下載文件的方法,非常具有實用價值,需要的朋友可以參考下

本文介紹了JAVA通過HttpURLConnection 上傳和下載文件的方法,分享給大家,具體如下:

HttpURLConnection文件上傳

HttpURLConnection采用模擬瀏覽器上傳的數(shù)據(jù)格式,上傳給服務(wù)器

上傳代碼如下:

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可用于發(fā)送HTTP請求,即java.net.URL、java.net.URLConnection,這些API很好用、很常用,
 * 但不夠簡便;
 * 
 * 1.通過統(tǒng)一資源定位器(java.net.URL)獲取連接器(java.net.URLConnection) 2.設(shè)置請求的參數(shù) 3.發(fā)送請求
 * 4.以輸入流的形式獲取返回內(nèi)容 5.關(guān)閉輸入流
 * 
 * @author H__D
 *
 */
public class HttpConnectionUtil {


 /**
  * 多文件上傳的方法
  * 
  * @param actionUrl:上傳的路徑
  * @param uploadFilePaths:需要上傳的文件路徑,數(shù)組
  * @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 {
   // 統(tǒng)一資源
   URL url = new URL(actionUrl);
   // 連接類的父類,抽象類
   URLConnection urlConnection = url.openConnection();
   // http的連接類
   HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;

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

   // 設(shè)置DataOutputStream
   ds = new DataOutputStream(httpURLConnection.getOutputStream());
   for (int i = 0; i < uploadFilePaths.length; i++) {
    String uploadFile = uploadFilePaths[i];
    String filename = uploadFile.substring(uploadFile.lastIndexOf("http://") + 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","http://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可用于發(fā)送HTTP請求,即java.net.URL、java.net.URLConnection,這些API很好用、很常用,
 * 但不夠簡便;
 * 
 * 1.通過統(tǒng)一資源定位器(java.net.URL)獲取連接器(java.net.URLConnection) 2.設(shè)置請求的參數(shù) 3.發(fā)送請求
 * 4.以輸入流的形式獲取返回內(nèi)容 5.關(guān)閉輸入流
 * 
 * @author H__D
 *
 */
public class HttpConnectionUtil {


 /**
  * 
  * @param urlPath
  *   下載路徑
  * @param downloadDir
  *   下載存放目錄
  * @return 返回下載文件
  */
 public static File downloadFile(String urlPath, String downloadDir) {
  File file = null;
  try {
   // 統(tǒng)一資源
   URL url = new URL(urlPath);
   // 連接類的父類,抽象類
   URLConnection urlConnection = url.openConnection();
   // http的連接類
   HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
   // 設(shè)定請求的方法,默認(rèn)是GET
   httpURLConnection.setRequestMethod("POST");
   // 設(shè)置字符編碼
   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");

 }

}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • SpringBoot2.0集成WebSocket實現(xiàn)后臺向前端推送信息

    SpringBoot2.0集成WebSocket實現(xiàn)后臺向前端推送信息

    這篇文章主要介紹了SpringBoot2.0集成WebSocket實現(xiàn)后臺向前端推送信息,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-01-01
  • 基于JAVA中的四種JSON解析方式詳解

    基于JAVA中的四種JSON解析方式詳解

    這篇文章主要介紹了基于JAVA中的四種JSON解析方式詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-09-09
  • JavaWeb中的常用的請求傳參注解說明

    JavaWeb中的常用的請求傳參注解說明

    這篇文章主要介紹了JavaWeb中的常用的請求傳參注解說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-04-04
  • 淺談十個常見的Java異常出現(xiàn)原因

    淺談十個常見的Java異常出現(xiàn)原因

    這篇文章主要介紹了十個常見的Java異常出現(xiàn)原因,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-03-03
  • Java使用poi包讀取Excel文檔代碼分享

    Java使用poi包讀取Excel文檔代碼分享

    這篇文章主要介紹了Java使用poi包讀取Excel文檔代碼分享,具有一定借鑒價值,需要的朋友可以參考下。
    2017-12-12
  • Java基于注解的Excel導(dǎo)出方式

    Java基于注解的Excel導(dǎo)出方式

    這篇文章主要介紹了Java基于注解的Excel導(dǎo)出方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-01-01
  • Java設(shè)計模式之迭代模式(Iterator模式)介紹

    Java設(shè)計模式之迭代模式(Iterator模式)介紹

    這篇文章主要介紹了Java設(shè)計模式之迭代模式(Iterator模式)介紹,本文用一個老師點名的現(xiàn)象描述了迭代模式的使用,需要的朋友可以參考下
    2015-03-03
  • 深入理解Java的接口與抽象類

    深入理解Java的接口與抽象類

    本文主要介紹java 的接口和抽象類,對接口和抽象類進(jìn)行介紹對比,深入理解,有需要的小伙伴可以參考下
    2016-07-07
  • 如何修改HttpServletRequest中header中的信息

    如何修改HttpServletRequest中header中的信息

    這篇文章主要介紹了如何修改HttpServletRequest中header中的信息,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-02-02
  • 【MyBatis源碼全面解析】MyBatis一二級緩存介紹

    【MyBatis源碼全面解析】MyBatis一二級緩存介紹

    下面小編就為大家?guī)硪黄綧yBatis源碼全面解析】MyBatis一二級緩存介紹。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-06-06

最新評論