JAVAでHttpURLConnectionを通じてファイルをアップロードし、ダウンロードする方法


本論文では、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
"; 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("
"); } } } 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 +
    // "%
"); } 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"); } }
以上が本文の全部です。皆さんの勉強に役に立つように、私たちを応援してください。