通过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 ...
随机推荐
- CF343E Pumping Stations(最小割树)
没学过最小割树的出门左转. 我们已经知道了两点的最小割就是最小割树上,对应两点之间路径的权值的最小值. 找到最小割树中权值的最小的边. 那么一定是先选完一侧的点在选完另一侧的点. 因为当前边最小,那么 ...
- Shell(四)函数
函数 linux shell 可以用户定义函数,然后在shell脚本中可以随便调用. 一.格式 shell中函数的定义格式如下: [ function ] funname [()] { action; ...
- ucore_lab0
一直想好好学习一下操作系统课程,去一个Mooc网站上找了一门操作系统的课程.这便是里面的配套实验. 实验指导:点这里 lab0主要是准备相关的操作环境.课程推荐使用qemu作为硬件模拟器,推荐运行环境 ...
- 【codeforces 799D】Field expansion
[题目链接]:http://codeforces.com/contest/799/problem/D [题意] 给你长方形的两条边h,w; 你每次可以从n个数字中选出一个数字x; 然后把h或w乘上x; ...
- java中new一个对象的执行过程及类的加载顺序
1,new一个对象时代码的执行顺序 (1)加载父类(以下序号相同,表明初始化是按代码从上到下的顺序来的) 1.为父类的静态属性分配空间并赋于初值 1.执行父类静态初始化块; (2)加载子类 2.为子类 ...
- ASP.NET-model验证
在ASP.NET的model中,可以定义下面的这种属性,来实现前台签证字符串 RegularExpression(@"(|.*(?=.{6,})(?=.*\d)(?=.*[a-zA-Z]). ...
- IOS版本号被拒的经历
IOS版本号被拒的经历: 1,登陆方式依赖外部平台 由于我们的APP是仅仅用微博登陆.想做成类似meerkat类型的.也能各种消息都同步微博. 结果当然行不通,这个确实是不听好人言.网上多个人都说过这 ...
- JDBC-Statement 对象
Statement 对象 一旦我们获得了数据库的连接,我们就可以和数据库进行交互.JDBC 的 Statement,CallableStatement 和 PreparedStatement 接口定义 ...
- 使用Powershell 的获取别的机器WMI类失败解决方法!
有些时候须要连接多台机器去获取他们的类,可是有些时候我们发现计算机无法连接,这个时候怎么办呢? 请改动组策略中下面配置: 能够使用Gpmc.msc 进行以后.本地计算机策略--计算机配置--管理模板- ...
- Android程序全然退出的三种方法
1. Dalvik VM的本地方法 android.os.Process.killProcess(android.os.Process.myPid()) //获取PID,眼下获取自己的也仅仅有该 ...