激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - JAVA通過HttpURLConnection 上傳和下載文件的方法

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

2021-01-10 11:57H__D Java教程

這篇文章主要介紹了JAVA通過HttpURLConnection 上傳和下載文件的方法,非常具有實用價值,需要的朋友可以參考下

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

HttpURLConnection文件上傳

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

上傳代碼如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
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文件下載

下載代碼如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
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.cnblogs.com/h--d/p/5638092.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 黄色片网站在线看 | 黄色特级一级片 | 国产成人77亚洲精品www | 久久精品亚洲精品国产欧美kt∨ | av成人在线免费观看 | 在线成人一区二区 | 亚洲导航深夜福利涩涩屋 | 色戒在线版 | xxxeexxx性国产 | 成年免费看 | av中文一区 | 久色免费 | 99精品国产在热久久婷婷 | 视频一区二区不卡 | 亚洲性视频 | 成人国产免费观看 | 欧美一区在线观看视频 | 国产成人av免费看 | 成人免费在线视频播放 | 国产一精品久久99无吗一高潮 | 久久色伦理资源站 | 双性精h调教灌尿打屁股的文案 | 国产午夜免费视频 | 成人一级黄色大片 | 国产日韩大片 | 国产精品久久久久久久午夜片 | 一级视频片 | 黄色视频a级毛片 | 国产亚洲高清在线精品不卡 | 亚洲精品成人18久久久久 | 成人羞羞在线观看网站 | 婷婷中文字幕一区二区三区 | 欧美黄色小视频 | 亚洲福利在线观看视频 | 久久亚洲精选 | 成人啪啪18免费网站 | 中文字幕精品一区久久久久 | chinese 军人 gay xx 呻吟 | 欧美一级淫片a免费播放口 九九视频精品在线 | 91久久国产综合精品女同国语 | 国产在线观看91一区二区三区 |