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. koa,express,node 通用方法连接MySQL

    这个教程不管node,express,koa都可以用下面方法连接,这里用koa做个参考 这个教程的源码地址: https://github.com/xiaqijian/... 新建文件目录,我是这样子 ...

  2. if判断语句

     6)if判断语句   if ... then   else   end if;     if ... then   elsif ... then   elsif ... then   else   ...

  3. NYIST 489 哭泣天使

    哭泣天使时间限制:1000 ms | 内存限制:65535 KB难度:5 描述Doctor Who乘着Tardis带着Amy来到了一个星球,一开Tadis大门,发现这个星球上有个壮观的石像群,全是一些 ...

  4. PC端 java 开发蓝牙所遇到的问题

    由于项目的原因.要在电脑上开发一个通过蓝牙传送数据的client.我採用的是JAVA,JSME开发. client:去搜素蓝牙信号,然后找到对应的蓝牙信号进行连接. 服务端:client须要进行连接的 ...

  5. mybatis和hibernate的区别【转】

    第一章     Hibernate与MyBatisHibernate 是当前最流行的O/R mapping框架,它出身于sf.net,现在已经成为Jboss的一部分. Mybatis 是另外一种优秀的 ...

  6. 本书已出版&lt;拨云见日:基于android的内核与系统架构源代码分析 &gt;

    已陆续倒到各大电商站点及新华书店 http://item.jd.com/11594135.html http://product.china-pub.com/4472138 http://www.am ...

  7. Non-ASCII character &#39;\xe8&#39; in file xxx.py on line 8, but no encoding declared

    使用网上某个python程序.编译时报错: File "xxx.py", line 8         SyntaxError: Non-ASCII character '\xe8 ...

  8. JavaScript事件驱动机制&amp;定时器机制

    在浏览器中,事件作为一个极为重要的机制,给予JavaScript响应用户操作与DOM变化的能力.在NodeJS中.异步事件驱动模型则是提高并发能力的基础. 一.程序怎样响应事件 程序响应外部的事件有两 ...

  9. codeblocks开源的c、c++编译器,小巧方便

    1.下载带gun的版本 2.设置编译的位置 3.创建项目 4.执行项目 有意思的开源的c编译器 ~~~

  10. apiCloud中实现头部与内容分离与操作规范,App头部header固定,头部与内容分离

    官方案例 1.头部拆分成一个页面比如news-text <!doctype html> <html> <head> <meta charset="u ...