通过HttpURLConnection 上传和下载文件(二)
HttpURLConnection文件上传
HttpURLConnection采用模拟浏览器上传的数据格式,上传给服务器
上传代码如下:
1 package com.util;
2
3 import java.io.BufferedInputStream;
4 import java.io.BufferedReader;
5 import java.io.DataOutputStream;
6 import java.io.File;
7 import java.io.FileInputStream;
8 import java.io.FileOutputStream;
9 import java.io.IOException;
10 import java.io.InputStream;
11 import java.io.InputStreamReader;
12 import java.io.OutputStream;
13 import java.io.OutputStreamWriter;
14 import java.net.HttpURLConnection;
15 import java.net.MalformedURLException;
16 import java.net.URL;
17 import java.net.URLConnection;
18 import java.util.Iterator;
19 import java.util.Map;
20
21 /**
22 * Java原生的API可用于发送HTTP请求,即java.net.URL、java.net.URLConnection,这些API很好用、很常用,
23 * 但不够简便;
24 *
25 * 1.通过统一资源定位器(java.net.URL)获取连接器(java.net.URLConnection) 2.设置请求的参数 3.发送请求
26 * 4.以输入流的形式获取返回内容 5.关闭输入流
27 *
28 * @author H__D
29 *
30 */
31 public class HttpConnectionUtil {
32
33
34 /**
35 * 多文件上传的方法
36 *
37 * @param actionUrl:上传的路径
38 * @param uploadFilePaths:需要上传的文件路径,数组
39 * @return
40 */
41 @SuppressWarnings("finally")
42 public static String uploadFile(String actionUrl, String[] uploadFilePaths) {
43 String end = "\r\n";
44 String twoHyphens = "--";
45 String boundary = "*****";
46
47 DataOutputStream ds = null;
48 InputStream inputStream = null;
49 InputStreamReader inputStreamReader = null;
50 BufferedReader reader = null;
51 StringBuffer resultBuffer = new StringBuffer();
52 String tempLine = null;
53
54 try {
55 // 统一资源
56 URL url = new URL(actionUrl);
57 // 连接类的父类,抽象类
58 URLConnection urlConnection = url.openConnection();
59 // http的连接类
60 HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
61
62 // 设置是否从httpUrlConnection读入,默认情况下是true;
63 httpURLConnection.setDoInput(true);
64 // 设置是否向httpUrlConnection输出
65 httpURLConnection.setDoOutput(true);
66 // Post 请求不能使用缓存
67 httpURLConnection.setUseCaches(false);
68 // 设定请求的方法,默认是GET
69 httpURLConnection.setRequestMethod("POST");
70 // 设置字符编码连接参数
71 httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
72 // 设置字符编码
73 httpURLConnection.setRequestProperty("Charset", "UTF-8");
74 // 设置请求内容类型
75 httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
76
77 // 设置DataOutputStream
78 ds = new DataOutputStream(httpURLConnection.getOutputStream());
79 for (int i = 0; i < uploadFilePaths.length; i++) {
80 String uploadFile = uploadFilePaths[i];
81 String filename = uploadFile.substring(uploadFile.lastIndexOf("//") + 1);
82 ds.writeBytes(twoHyphens + boundary + end);
83 ds.writeBytes("Content-Disposition: form-data; " + "name=\"file" + i + "\";filename=\"" + filename
84 + "\"" + end);
85 ds.writeBytes(end);
86 FileInputStream fStream = new FileInputStream(uploadFile);
87 int bufferSize = 1024;
88 byte[] buffer = new byte[bufferSize];
89 int length = -1;
90 while ((length = fStream.read(buffer)) != -1) {
91 ds.write(buffer, 0, length);
92 }
93 ds.writeBytes(end);
94 /* close streams */
95 fStream.close();
96 }
97 ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
98 /* close streams */
99 ds.flush();
100 if (httpURLConnection.getResponseCode() >= 300) {
101 throw new Exception(
102 "HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
103 }
104
105 if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
106 inputStream = httpURLConnection.getInputStream();
107 inputStreamReader = new InputStreamReader(inputStream);
108 reader = new BufferedReader(inputStreamReader);
109 tempLine = null;
110 resultBuffer = new StringBuffer();
111 while ((tempLine = reader.readLine()) != null) {
112 resultBuffer.append(tempLine);
113 resultBuffer.append("\n");
114 }
115 }
116
117 } catch (Exception e) {
118 // TODO Auto-generated catch block
119 e.printStackTrace();
120 } finally {
121 if (ds != null) {
122 try {
123 ds.close();
124 } catch (IOException e) {
125 // TODO Auto-generated catch block
126 e.printStackTrace();
127 }
128 }
129 if (reader != null) {
130 try {
131 reader.close();
132 } catch (IOException e) {
133 // TODO Auto-generated catch block
134 e.printStackTrace();
135 }
136 }
137 if (inputStreamReader != null) {
138 try {
139 inputStreamReader.close();
140 } catch (IOException e) {
141 // TODO Auto-generated catch block
142 e.printStackTrace();
143 }
144 }
145 if (inputStream != null) {
146 try {
147 inputStream.close();
148 } catch (IOException e) {
149 // TODO Auto-generated catch block
150 e.printStackTrace();
151 }
152 }
153
154 return resultBuffer.toString();
155 }
156 }
157
158
159 public static void main(String[] args) {
160
161 // 上传文件测试
162 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" });
163 System.out.println(str);
164
165
166 }
167
168 }uploadFile
HttpURLConnection文件下载
下载代码如下:
1 package com.util;
2
3 import java.io.BufferedInputStream;
4 import java.io.BufferedReader;
5 import java.io.DataOutputStream;
6 import java.io.File;
7 import java.io.FileInputStream;
8 import java.io.FileOutputStream;
9 import java.io.IOException;
10 import java.io.InputStream;
11 import java.io.InputStreamReader;
12 import java.io.OutputStream;
13 import java.io.OutputStreamWriter;
14 import java.net.HttpURLConnection;
15 import java.net.MalformedURLException;
16 import java.net.URL;
17 import java.net.URLConnection;
18 import java.util.Iterator;
19 import java.util.Map;
20
21 /**
22 * Java原生的API可用于发送HTTP请求,即java.net.URL、java.net.URLConnection,这些API很好用、很常用,
23 * 但不够简便;
24 *
25 * 1.通过统一资源定位器(java.net.URL)获取连接器(java.net.URLConnection) 2.设置请求的参数 3.发送请求
26 * 4.以输入流的形式获取返回内容 5.关闭输入流
27 *
28 * @author H__D
29 *
30 */
31 public class HttpConnectionUtil {
32
33
34 /**
35 *
36 * @param urlPath
37 * 下载路径
38 * @param downloadDir
39 * 下载存放目录
40 * @return 返回下载文件
41 */
42 public static File downloadFile(String urlPath, String downloadDir) {
43 File file = null;
44 try {
45 // 统一资源
46 URL url = new URL(urlPath);
47 // 连接类的父类,抽象类
48 URLConnection urlConnection = url.openConnection();
49 // http的连接类
50 HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
51 // 设定请求的方法,默认是GET
52 httpURLConnection.setRequestMethod("POST");
53 // 设置字符编码
54 httpURLConnection.setRequestProperty("Charset", "UTF-8");
55 // 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。
56 httpURLConnection.connect();
57
58 // 文件大小
59 int fileLength = httpURLConnection.getContentLength();
60
61 // 文件名
62 String filePathUrl = httpURLConnection.getURL().getFile();
63 String fileFullName = filePathUrl.substring(filePathUrl.lastIndexOf(File.separatorChar) + 1);
64
65 System.out.println("file length---->" + fileLength);
66
67 URLConnection con = url.openConnection();
68
69 BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
70
71 String path = downloadDir + File.separatorChar + fileFullName;
72 file = new File(path);
73 if (!file.getParentFile().exists()) {
74 file.getParentFile().mkdirs();
75 }
76 OutputStream out = new FileOutputStream(file);
77 int size = 0;
78 int len = 0;
79 byte[] buf = new byte[1024];
80 while ((size = bin.read(buf)) != -1) {
81 len += size;
82 out.write(buf, 0, size);
83 // 打印下载百分比
84 // System.out.println("下载了-------> " + len * 100 / fileLength +
85 // "%\n");
86 }
87 bin.close();
88 out.close();
89 } catch (MalformedURLException e) {
90 // TODO Auto-generated catch block
91 e.printStackTrace();
92 } catch (IOException e) {
93 // TODO Auto-generated catch block
94 e.printStackTrace();
95 } finally {
96 return file;
97 }
98
99 }
100
101 public static void main(String[] args) {
102
103 // 下载文件测试
104 downloadFile("http://localhost:8080/images/1467523487190.png", "/Users/H__D/Desktop");
105
106 }
107
108 }downloadFile
通过HttpURLConnection 上传和下载文件(二)的更多相关文章
- 【JAVA】通过HttpURLConnection 上传和下载文件(二)
HttpURLConnection文件上传 HttpURLConnection采用模拟浏览器上传的数据格式,上传给服务器 上传代码如下: package com.util; import java.i ...
- 11、只允许在主目录下上传和下载文件,不允许用putty登录
创建用户xiao, 使其只允许在用户主目录 (/var/www/html)下上传和下载文件,不允许用putty登录 (为了安全起见,不给过多的权限) 1.创建xiao用户 [root@localh ...
- 每天一个linux命令(26):用SecureCRT来上传和下载文件
用SSH管理linux服务器时经常需要远程与本地之间交互文件.而直接用SecureCRT自带的上传下载功能无疑是最方便的,SecureCRT下的文件传输协议有ASCII.Xmodem.Zmodem. ...
- Linux--用SecureCRT来上传和下载文件
SecureCRT下的文件传输协议有以下几种:ASCII.Xmodem.Ymodem.Zmodem ASCII:这是最快的传输协议,但只能传送文本文件. Xmodem:这种古老的传输协议速度较慢,但由 ...
- 每天一个linux命令(26)--用SecureCRT来上传和下载文件
用SSH管理Linux 服务器时经常需要远程与本地之间交互文件,而直接使用 SecureCRT 自带的上传下载功能无疑是最方便的,SecureCRT下的文件传输协议有ASCII.Xmodem.Zmod ...
- 每天一个linux命令(26):用SecureCRT来上传和下载文件(转载自竹子)
用SSH管理linux服务器时经常需要远程与本地之间交互文件.而直接用SecureCRT自带的上传下载功能无疑是最方便的,SecureCRT下的文件传输协议有ASCII.Xmodem.Zmodem. ...
- 用SecureCRT来上传和下载文件
用SSH管理linux服务器时经常需要远程与本地之间交互文件.而直接用SecureCRT自带的上传下载功能无疑是最方便的,SecureCRT下的文件传输协议有ASCII.Xmodem.Zmodem. ...
- Spring Boot之 Controller 接收参数和返回数据总结(包括上传、下载文件)
一.接收参数(postman发送) 1.form表单 @RequestParam("name") String name 会把传递过来的Form表单中的name对应 ...
- Linux (rz、sz命令行)与本地电脑 命令行上传、下载文件
Linux 与本地电脑直接交互, 命令行上传.下载文件. 一.lrzsz命令行安装: 1.rpm安装:(链接: http://pan.baidu.com/s/1cBuTm2 密码: vijf) rpm ...
随机推荐
- cf掉分记——Avito Code Challenge 2018
再次作死的打了一次cf的修仙比赛感觉有点迷.. 还好掉的分不多(原本就太低没法掉了QAQ) 把会做的前三道水题记录在这.. A: Antipalindrome emmmm...直接暴力枚举 code: ...
- jquery 用于操作动态元素的delegate/on方法
delegate() 方法的事件处理程序适用于当前或未来的元素(比如由脚本创建的新元素). 在做项目中有很多由ajax动态生成的html标签,jquery对这些标签不会响应\((selector).c ...
- 异构关系数据库(Sqlserver与Oracle)之间的数据类型转换参考
一.Oracle到SqlServer的数据类型的转变 编号 Oracle ToSqlServer SqlServer 1 BINARY_DOUBLE VARCHAR(100) real 2 BINAR ...
- COGS——T 1175. [顾研NOIP] 旅游电车
http://www.cogs.pro/cogs/problem/problem.php?pid=1175 ★★☆ 输入文件:buss.in 输出文件:buss.out 简单对比时间限制: ...
- ruby on rails错误undefined method `title' for nil:NilClass
首先搞清楚这句话,在 Ruby 中,方法分为 public.private 和 protected 三种,仅仅有 public 方法才干作为控制器的动作. 我的出错的代码例如以下: controlle ...
- c#将List<T>转换成DataSet
/// <summary> /// List<T> 转换成DataSet /// </summary> /// &l ...
- Redis-4-链表结构
Redis-4-链表结构 标签(空格分隔):redis lpush key value 作用: 把值插入到链接头部 rpop key 作用: 返回并删除链表尾元素 lrange key start s ...
- Android TextView加上阴影效果
<TextView android:id="@+id/test_shadow" android:layout_width="wrap_content" a ...
- Windows环境下使用Guard整合Compass和Livereload进行SASS的开发
配置运行环境 Guard,Compass 和 Livereload 是 Ruby 的 Gem 套件,需要 Ruby 运行环境.另外还需要安装 Ruby 的扩展开发包 Development-Kit,以 ...
- 快速傅里叶变换(Fast-Fourier Transform,FFT)
数学定义: (详细参考:https://www.baidu.com/link?url=oYAuG2o-pia_U3DlF5n_MJZyE5YKfaVRUHTTDbM1FwM_kDTjGCxKpw_Pb ...