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 上传和下载文件(二)的更多相关文章

  1. 【JAVA】通过HttpURLConnection 上传和下载文件(二)

    HttpURLConnection文件上传 HttpURLConnection采用模拟浏览器上传的数据格式,上传给服务器 上传代码如下: package com.util; import java.i ...

  2. 11、只允许在主目录下上传和下载文件,不允许用putty登录

    创建用户xiao,   使其只允许在用户主目录 (/var/www/html)下上传和下载文件,不允许用putty登录 (为了安全起见,不给过多的权限) 1.创建xiao用户 [root@localh ...

  3. 每天一个linux命令(26):用SecureCRT来上传和下载文件

    用SSH管理linux服务器时经常需要远程与本地之间交互文件.而直接用SecureCRT自带的上传下载功能无疑是最方便的,SecureCRT下的文件传输协议有ASCII.Xmodem.Zmodem. ...

  4. Linux--用SecureCRT来上传和下载文件

    SecureCRT下的文件传输协议有以下几种:ASCII.Xmodem.Ymodem.Zmodem ASCII:这是最快的传输协议,但只能传送文本文件. Xmodem:这种古老的传输协议速度较慢,但由 ...

  5. 每天一个linux命令(26)--用SecureCRT来上传和下载文件

    用SSH管理Linux 服务器时经常需要远程与本地之间交互文件,而直接使用 SecureCRT 自带的上传下载功能无疑是最方便的,SecureCRT下的文件传输协议有ASCII.Xmodem.Zmod ...

  6. 每天一个linux命令(26):用SecureCRT来上传和下载文件(转载自竹子)

    用SSH管理linux服务器时经常需要远程与本地之间交互文件.而直接用SecureCRT自带的上传下载功能无疑是最方便的,SecureCRT下的文件传输协议有ASCII.Xmodem.Zmodem. ...

  7. 用SecureCRT来上传和下载文件

    用SSH管理linux服务器时经常需要远程与本地之间交互文件.而直接用SecureCRT自带的上传下载功能无疑是最方便的,SecureCRT下的文件传输协议有ASCII.Xmodem.Zmodem. ...

  8. Spring Boot之 Controller 接收参数和返回数据总结(包括上传、下载文件)

            一.接收参数(postman发送) 1.form表单 @RequestParam("name") String name 会把传递过来的Form表单中的name对应 ...

  9. Linux (rz、sz命令行)与本地电脑 命令行上传、下载文件

    Linux 与本地电脑直接交互, 命令行上传.下载文件. 一.lrzsz命令行安装: 1.rpm安装:(链接: http://pan.baidu.com/s/1cBuTm2 密码: vijf) rpm ...

随机推荐

  1. 如何设置,获取,删除cookie?

    cookie : 存储数据,当用户访问了某个网站(网页)的时候,我们就可以通过cookie来像访问者电脑上存储数据 1.不同的浏览器存放的cookie位置不一样,也是不能通用的 2.cookie的存储 ...

  2. PHP的迭代器和生成器

    一.迭代器 分析:想一下,如果把集合对象和对集合对象的操作放在一起,当我们想换一种方式遍历集合对象中元素时,就需要修改集合对象了,违背"单一职责原则",而迭代器模式将数据结构和数据 ...

  3. django-4-模板标签,模板继承

    <<<模板标签>>> {% for %}{% endfor %} 循环 {% if %}{% elif %}{% else %}{% endif %} 判断 {% ...

  4. JS中常用开发知识点

     JS中常用开发知识点 1.获取指定范围内的随机数 2.随机获取数组中的元素 3.生成从0到指定值的数字数组 等同于: 4.打乱数字数组的顺序 5.对象转换为数组 //注意对象必须是以下格式的才可以通 ...

  5. hiho模拟面试题2 补提交卡 (贪心,枚举)

    题目: 时间限制:2000ms 单点时限:1000ms 内存限制:256MB 描写叙述 小Ho给自己定了一个雄伟的目标:连续100天每天坚持在hihoCoder上提交一个程序.100天过去了.小Ho查 ...

  6. dpdk l2fwd 应用流程分析

    int MAIN(int argc, char **argv) { struct lcore_queue_conf *qconf; struct rte_eth_dev_info dev_info; ...

  7. Oracle 12c agent install for windows

    在Oracle EM12c 中部署agent的方法分两种,一种是通过EM12c的控制台通过ssh直接把agent"推送"安装到被管理端.这样的方法在linux平台的OMS和被管理端 ...

  8. rails数据库操作rake db一点心得

    问题描述,对于很多的新手rails lover来说,搞定db是件头疼的事情,当建立了一个model,测试了半天发现我草列名写错了,再过一会儿发现association里面竟然没有xxx_id,这下子s ...

  9. mysql读写分离原理及配置

    1 复制概述 Mysql内建的复制功能是构建大型,高性能应用程序的基础.将Mysql的数据分布到多个系统上去,这种分布的机制,是通过将Mysql的某一台主机的数据复制到其它主机(slaves)上,并重 ...

  10. Android PullToRefreshListView设置各个item之间的间距

    要设置第三方的上拉下载listView的item之间的间距,可以在xml布局文件中的listView节点中设置xml的属性即可: android:divider="#00000000&quo ...