HttpURLConnection文件上传

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

  上传代码如下:

  • 通过HttpURLConnection 上传和下载文件(二)_java通过HttpURLConnection 上传和下载文件(二)_.net_02

    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文件下载

  下载代码如下:

  • 通过HttpURLConnection 上传和下载文件(二)_java通过HttpURLConnection 上传和下载文件(二)_.net_02

    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