java http 下載文件_JAVA通過HttpURLConnection 上傳和下載文件的方法

本文介紹了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");

}

}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/539099.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/539099.shtml
英文地址,請注明出處:http://en.pswp.cn/news/539099.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

mkdir-yum-tree命令應用案例

案例&#xff1a; 請用一條命令完成目錄創建/hello/world/test 解答&#xff1a; mkdir -p /hello/world/test -p 遞歸創建目錄&#xff0c;沒有子目錄創建。 案例&#xff1a; 打印hello/目錄的結構 [roothello110 ~]# tree hello/ -bash: tree: command not found 發…

pytorch 圖像分割的交并比_Segmentation101系列-最簡單的卷積網絡語義分割(1)-PASCAL VOC圖像分割...

作者&#xff1a;陳洪瀚 /洪瀚筆記知乎專欄摘要&#xff1a;介紹了使用PyTorch和torchvision加載訓練好的全卷積網絡FCN或DeepLab模型&#xff0c;并對PASCAL VOC圖像進行分割并顯示結果。網址&#xff1a;github代碼鏈接, 碼云代碼鏈接陳洪瀚?www.zhihu.com一. 準備實驗數據下…

python selenium chrome獲取每個請求內容_python+selenium調用chrome打開網址獲取內容

通過selenium庫&#xff0c;python可以調用chrome打開指定網頁并獲取網頁內容或者模擬登陸獲取網頁內容1&#xff0c;安裝selenium和配置chromedriver安裝seleniumC:\Users\cord> pip install selenium配置chromedriver該下載什么版本根據瀏覽器版本以及附錄的版本對照表下載…

系統目錄結構 ls命令 文件類型 alias命令

2019獨角獸企業重金招聘Python工程師標準>>> 2.1/2.2 系統目錄結構 /bin&#xff1a;bin是Binary的縮寫&#xff0c;該目錄下存放的是最常用的命令。 /boot&#xff1a;該目錄下存放的是啟動Linux時使用的一些核心文件&#xff0c;包括一些連接文件以及鏡像文件。 …

運維老鳥教你安裝centos6.5如何選擇安裝包

原文&#xff1a;http://oldboy.blog.51cto.com/2561410/1564620 ------------------------------------------------------------------------------ 近來發現越來越多的運維小伙伴們都有最小化安裝系統的潔癖,因此&#xff0c;找老男孩來咨詢&#xff0c;這個“潔癖”好習慣…

服務器centos怎么部署_我什么都不會,怎么擁有自己的個人博客呢

博客每個人都想擁有一個屬于自己的博客&#xff0c;可以分享自己的心得、技術等&#xff0c;可以很好地展示自己的作品&#xff0c;但是自己又什么都不會怎么才能擁有自己的個人博客呢&#xff1f;一、搭建個人博客需要什么呢(1)購買服務器&#xff0c;個人博客可以購買香港服務…

java 過濾器 過濾文件中的文件_Java 使用FileFilter過濾器對文件進行搜索

FileFilter概述java.io.FileFilter是一個接口&#xff0c;是File的過濾器。該接口的對象可以傳遞給File類的listFiles(FileFilter filter)作為參數&#xff0c;FileFilter接口中只有一個方法。boolean accept(File pathname):測試pathname是否應該包含在當前File目錄中&#xf…

修改yum的鏡像服務器為阿里云

1、進入阿里云鏡像網站 http://mirrors.aliyun.com/ 2、選擇centos---help 3、安裝help里的步驟進行操作 1、備份 mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup 2、下載新的CentOS-Base.repo 到/etc/yum.repos.d/ CentOS 5 wget -O /e…

面試記錄

東信北郵 智能終端開發工程師 筆試部分 首先去做了一套筆試題&#xff0c;前面選擇題都是android基礎&#xff0c;后面是sql語句。 有一個問題說的是runtime exception&#xff0c;有四個選項&#xff1a; a. ArithmeticException b. lllegalArgumentException c. NullPointerE…

python有類似mybatis的框架_為什么感覺國內比較流行的 mybatis 在國外好像沒人用的樣子?...

892019-03-30 21:23:21 08:00 1看了這么多回復。忍不住了&#xff01;1. hibernate 歷史悠久并不代表過時&#xff0c;mybatis 這種方式就是未來嗎&#xff1f;肯定不是。數據庫就是用來存數據的&#xff0c;聯表查詢一大堆只能說明數據結構設計是有問題的&#xff0c;只是不…

c# 模擬登陸 webbrowser 抓取_《VR+電力——更換絕緣子培訓》已登陸Pico Neo 2

原標題&#xff1a;《VR電力——更換絕緣子培訓》已登陸Pico Neo 2

java instanceof 繼承_Java中的instanceof關鍵字

Java中&#xff0c;instanceof運算符的前一個操作符是一個引用變量&#xff0c;后一個操作數通常是一個類(可以是接口)&#xff0c;用于判斷前面的對象是否是后面的類&#xff0c;或者其子類、實現類的實例。如果是返回true&#xff0c;否則返回false。也就是說&#xff1a;使用…

中文導致Mybatis無效的列索引

<!-- 普鐵 --><select id"selectTrainSceneThrough" parameterType"HashMap" resultType"HashMap">select ROUND(("普鐵用戶專網總流量KB""普鐵用戶公網總流量KB")/1024/1024,3) as total_dataflow,"普鐵用…

python怎么創建配置文件_如何寫python的配置文件

一、創建配置文件在D盤建立一個配置文件&#xff0c;名字為&#xff1a;test.ini內容如下&#xff1a;[baseconf]host127.0.0.1port3306userrootpasswordrootdb_namegloryroad[test]ip127.0.0.1int1float1.5boolTrue注意&#xff1a;要將文件保存為ansi編碼&#xff0c;utf-8編…

學習筆記-JMeter 進行接口壓力測試

一、壓力測試場景設置 1、場景設定&#xff1a;進行接口壓力測試時&#xff0c;有單場景也有混合場景。單場景就是對一個接口進行請求&#xff1b;混合場景需要對多個接口進行請求&#xff0c;在流程類業務場景會運用到 2、壓測時間設定&#xff1a;通常時間為10&#xff0d;15…

Linux的 .bashrc 和.bash_profile和.profile文件

linux啟動或是每次打開一個shell的時候都會執行用戶家目錄下的.bashrc文件&#xff0c;所有可以在這個文件里面添加一些內容&#xff0c;以便Linux每次啟動時都會執行相應的內容。 如果ssh方式遠程登錄Linux時&#xff0c;會自動執行用戶家目錄下的.bash_profile文件&#xff0…

四宮格效果 css_【深度教研】智力游戲“九宮格” 集體教研活動紀實

【關鍵詞】教研要建立過程模式&#xff0c;規范管理&#xff0c;分層推進&#xff0c;各負其責&#xff0c;及時反饋&#xff0c;展示總結。讓教研的過程成為全體教師共同成長的過程。游戲和材料不是一次性的制作和一次性的使用&#xff0c;其價值在于反復玩&#xff0c;玩中學…

java oracle 排序_Oracle的排序和限制條件(order by 和where)

1、Order by子句的使用select column....from ....order by ...1) Order by子句在整個select語句中的位置&#xff1a;始終位于最后2) order by后可以跟什么&#xff1a;列名&#xff0c;列的別名&#xff0c;表達式&#xff0c;列出現在select關鍵字后的順序(列號);3) order b…

kettle使用_ETL工具(kettle)-《PentahoKettle解決方案-使用PDI構建開源ETL解決方案》

&#xfeff;Matt Casters的博客:http://www.ibridge.be/、 www.kettle.be書籍:《Pentaho Kettle解決方案&#xff1a;使用PDI構建開源ETL解決方案》 鏈接&#xff1a;https://pan.baidu.com/s/15iUOWOCb8g_YLo5WN9fh0A 提取碼&#xff1a;5upfkettle起源Kettle一詞起源于“KDE…

Linux下chkconfig命令詳解

原文&#xff1a;http://www.cnblogs.com/panjun-Donet/archive/2010/08/10/1796873.html ------------------------------ chkconfig命令主要用來更新&#xff08;啟動或停止&#xff09;和查詢系統服務的運行級信息。謹記chkconfig不是立即自動禁止或激活一個服務&#xff0…