Java客户端基于http上传文件的两种方式

java客户端基于http上传文件的两种方式:

apache的HttpClient 与 jdk的HttpURLConnection

各自实现代码

package com.wx.controller;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
/**
 * http后台上传文件
 * 
 * @author 王旭
 * 
 */
public class HttpUpload {
 /**
  * 基于httpClient上传文件
  * 
  * @param file
  *            文件
  * @param uploadUrl
  *            上传的url
  * @return
  * @throws IOException
  */
 public String uploadFileWithHttpClient(File file, String uploadUrl)
   throws IOException {
  String response = "";
  if (!file.exists()) {
   return "file not exists";
  }
  PostMethod postMethod = new PostMethod(uploadUrl);
  try {
   // FilePart:用来上传文件的类
   FilePart fp = new FilePart("filedata", file);
   Part[] parts = { fp };
   // 对于MIME类型的请求,httpclient建议全用MulitPartRequestEntity进行包装
   MultipartRequestEntity mre = new MultipartRequestEntity(parts,
     postMethod.getParams());
   postMethod.setRequestEntity(mre);
   HttpClient client = new HttpClient();
   client.getHttpConnectionManager().getParams()
     .setConnectionTimeout(50000);
   int status = client.executeMethod(postMethod);
   if (status == HttpStatus.SC_OK) {
    InputStream inputStream = postMethod.getResponseBodyAsStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(
      inputStream));
    StringBuffer stringBuffer = new StringBuffer();
    String str = "";
    while ((str = br.readLine()) != null) {
     stringBuffer.append(str);
    }
    response = stringBuffer.toString();
   } else {
    response = "fail";
   }
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   postMethod.releaseConnection();
  }
  return response;
 }
 /**
  * 基于HttpUrlConnection上传文件
  * 
  * @param inputStream
  *            文件流(流File类型更抽象)
  * @param fileName
  *            文件名
  * @param uploadUrl
  *            上传的url
  * @return
  * @throws MalformedURLException
  */
 public String uploadFileWithHttpUrlConnection(InputStream inputStream,
   String fileName, String uploadUrl) throws Exception {
  /* 边界、分隔 */
  String end = "\r\n";
  String twoHyphens = "--";
  String boundary = "*****";
  URL url = new URL(uploadUrl);
  HttpURLConnection con = (HttpURLConnection) url.openConnection();
  con.setDoInput(true);
  con.setDoOutput(true);
  con.setUseCaches(false);
  con.setRequestMethod("POST");
  con.setRequestProperty("Connection", "Keep-Alive");
  con.setRequestProperty("Charset", "UTF-8");
  con.setRequestProperty("Content-Type", "multipart/form-data;boundary="
    + boundary);
  DataOutputStream ds = new DataOutputStream(con.getOutputStream());
  ds.writeBytes(twoHyphens + boundary + end);
  ds.writeBytes("Content-Disposition: form-data; "
    + "name=\"file\";filename=\"" + fileName + "\" " + end);
  ds.writeBytes(end);
  /* 文件较大时一定要设置缓冲区,防止内存溢出 */
  int bufferSize = 1024;
  byte[] buffer = new byte[bufferSize];
  int length = -1;
  /* 循环将流输出 */
  while ((length = inputStream.read(buffer)) != -1) {
   ds.write(buffer, 0, length);
  }
  ds.writeBytes(end);
  ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
  inputStream.close();
  ds.flush();
  /* 读取响应 */
  BufferedReader br = new BufferedReader(new InputStreamReader(
    con.getInputStream()));
  StringBuffer stringBuffer = new StringBuffer();
  String str = "";
  while ((str = br.readLine()) != null) {
   stringBuffer.append(str);
  }
  return stringBuffer.toString();
 }
}

 

两种方式比较

HttpClient更简单,但只能接受具体的File对象作为参数;

HttpURLConnection更底层,但可以接受InputStream作为参数;

 

工作中遇到的问题

公司网站可能使用“乐视云视频接口" , 流程是:网站页面上传视频--->网站后台接收--->转发至乐视云平台

因公司网站的文件上传使用的是spring mvc,控制器接收的参数为MultipartFile,但这个类没办法转为File类型,同时因为没有必要先将用户视频存在公司服务器(即新建一个File),于是就否定了用HttpClient传输文件的方法;改为HttpURLConnection方式,接收流 。InputStream is = multipartFile.getInputStream();//MultipartFile获取流

你可能感兴趣的:(java,上传文件,http上传文件)