当前位置: 移动技术网 > IT编程>开发语言>Java > JAVA通过HttpURLConnection 上传和下载文件的方法

JAVA通过HttpURLConnection 上传和下载文件的方法

2019年07月19日  | 移动技术网IT编程  | 我要评论

本文介绍了java通过httpurlconnection 上传和下载文件的方法,分享给大家,具体如下:

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


 }

}

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

 }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网