HttpURLConnection文件上传

  HttpURLConnection采用模拟浏览器上传的数据格式,上传给服务器

  上传代码如下:

  •  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); } }

    uploadFile

HttpURLConnection文件下载

  下载代码如下:

  •  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"); } }

    downloadFile

  

  

【JAVA】通过HttpURLConnection 上传和下载文件(二)的更多相关文章

  1. Java 利用FTP上传,下载文件,遍历文件目录

    Java实现FTP上传下载文件的工具包有很多,这里我采用Java自带的API,实现FTP上传下载文件.另外JDK1.7以前的版本与其之后版本的API有了较大的改变了. 例如: JDK1.7之前 JDK ...

  2. 通过HttpURLConnection 上传和下载文件(二)

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

  3. ftp上传或下载文件工具类

    FtpTransferUtil.java工具类,向ftp上传或下载文件: package utils; import java.io.File; import java.io.FileOutputSt ...

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

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

  5. SecureCRT上传和下载文件

    SecureCRT上传和下载文件(下载默认目录) SecureCR 下的文件传输协议有ASCII .Xmodem .Ymodem .Zmodem ASCII:这是最快的传输协议,但只能传送文本文件. ...

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

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

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

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

  8. 利用SecureCRT上传、下载文件(使用sz与rz命令),超实用!

    利用SecureCRT上传.下载文件(使用sz与rz命令),超实用! 文章来源:http://blog.csdn.net/dongqinliuzi/article/details/39623169 借 ...

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

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

随机推荐

  1. linux获取日志指定行数范围内的内容

    假如我要获取“浅浅岁月拂满爱人袖”到“落入凡尘伤情着我”之间的内容. 1.首先得到他们所在的行号: -n选项显示行号 但是有时候grep后显示的是“匹配到二进制文件(标准输入)”,说明搜索的字符串在某 ...

  2. xml转json的方法

    .第一种方法 使用JSON-JAVA提供的方法,之前一直使用json-lib提供的方法转json,后来发现了这个开源项目,觉得用起来很不错,并且可以修改XML.java中的parse方法满足自己的转换 ...

  3. redis详解(四)-- 高可用分布式集群

    一,高可用 高可用(High Availability),是当一台服务器停止服务后,对于业务及用户毫无影响. 停止服务的原因可能由于网卡.路由器.机房.CPU负载过高.内存溢出.自然灾害等不可预期的原 ...

  4. Linux tomcat启动慢, Creation of SecureRandom instance for session ID generation using [SHA1PRNG]took [xx] mil

    启动慢的解决链接:  http://blog.csdn.net/u011627980/article/details/54024974

  5. as3 有趣现象 关于声明与变量

    当使用了一个变量,并且前后期都没有在有效域内对此声明,不管有没有赋值,都会报错. 但先使用了一个变量,后期在有效域内对此声明,那么此变量不报错,但在声明之前没有赋值,那么赋值默认值:如果使用变量时,赋 ...

  6. 安装oracle后java -version命令显示 jdk version "1.3.1"的原因

    因为先装的JDK,后装了oracle,oracle的JDK配置把原来的jdk路径替换掉了. 我的电脑->属性->高级->环境变量->系统变量->PATH ,把JDK的路径 ...

  7. 【348】通过 Numpy 创建各式各样的矩阵

    参考:NumPy之array-一个程序媛的自我修养-51CTO博客 参考:numpy中数组和矩阵的区别 - jiangsujiangjiang的博客 - CSDN博客 一.使用系统方法 二.用指定的数 ...

  8. \extras\intel\Hardware_Accelerated_Execution_Manager HAXM 未安装导致AndroidStudio新建了模拟器开启不了

    之前安装过 bios模式也是正常的.所以按照下面的步骤操作. https://software.intel.com/en-us/android  在这个界面 选择右侧的, 下载后解压到下面图上的路径: ...

  9. Struct2总结

    摘自<javaWeb整合开发王者归来> 一.Struct2工作流程 1.访问jsp页面  /struts2/login.jsp 2.提交表单后数据提交给 /struts2/loginPer ...

  10. 第八章 高级搜索树 (xa2)红黑树:结构