用HttpURLConnection提交文件

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class HttpMultipart
{
public static void main(String[] args) throws Exception
{
String link = “http://www.xxx.com/upload“;
HttpMultipart hm = new HttpMultipart(link).addParameter(“file”, new File(“d:\xxx.doc”)).addParameter(“other”,”somevalue”);
String result = new String(hm.send());
hm.clearParameter();
System.out.println(result);

}

private URL url;// 链接URL

private String boundary = "--------" + UUID.randomUUID().toString().replace("-", "");// HTTP报文分隔符

private Map<String, List<String>> textParams = new HashMap<String, List<String>>();// 字符串表单存储结构

private Map<String, List<File>> fileParams = new HashMap<String, List<File>>();// 文件表单存储结构

public HttpMultipart(String url) throws Exception
{
    this.url = new URL(url);
}

protected Map<String, List<File>> getFileParams()
{
    return fileParams;
}

protected Map<String, List<String>> getTextParams()
{
    return textParams;
}

// 增加一个普通字符串数据到form表单数据中
public HttpMultipart addParameter(String name, String value)
{
    List<String> list = textParams.get(name);
    if (list == null)
    {
        list = new LinkedList<String>();
        list.add(value);
        textParams.put(name, list);
    }
    else
    {
        list.add(value);
    }
    return this;
}

// 增加一个文件到form表单数据中
public HttpMultipart addParameter(String name, File value)
{
    List<File> list = fileParams.get(name);
    if (list == null)
    {
        list = new LinkedList<File>();
        list.add(value);
        fileParams.put(name, list);
    }
    else
    {
        list.add(value);
    }
    return this;
}

// 删除指定的字符串参数
public HttpMultipart removeTextParameter(String name)
{
    textParams.remove(name);
    return this;
}

// 删除指定的字符串参数(如果是数组,指定数组下标)
public HttpMultipart removeTextParameter(String name, int index)
{
    List<String> list = textParams.get(name);
    if (list != null)
    {
        if (list.size() > index)
        {
            list.remove(index);
        }
        if (list.size() == 0)
        {
            textParams.remove(name);
        }
    }
    return this;
}

// 删除指定的文件参数
public HttpMultipart removeFileParameter(String name)
{
    fileParams.remove(name);
    return this;
}

// 删除指定的文件参数(如果是数组,指定数组下标)
public HttpMultipart removeFileParameter(String name, int index)
{
    List<File> list = fileParams.get(name);
    if (list != null)
    {
        if (list.size() > index)
        {
            list.remove(index);
        }
        if (list.size() == 0)
        {
            fileParams.remove(name);
        }
    }
    return this;
}

// 清除字符串参数
public HttpMultipart clearTextParameter()
{
    textParams.clear();
    return this;
}

// 清除文件参数
public HttpMultipart clearFileParameter()
{
    fileParams.clear();
    return this;
}

// 清除所有参数
public HttpMultipart clearParameter()
{
    textParams.clear();
    fileParams.clear();
    return this;
}

// 发送数据到服务器,返回一个字节包含服务器的返回结果的数组
public byte[] send() throws Exception
{
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    long length = getLength();
    connection.setDoOutput(true);
    connection.setUseCaches(false);
    connection.setConnectTimeout(10000); // 连接超时为10秒
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    connection.setRequestProperty("Content-Length", length + "");
    // connection.setFixedLengthStreamingMode((int) length);//设置上传流大小,防止OutOfMemoryError;但是Int的最大值只支持2G,所以暂时不用;
    connection.setChunkedStreamingMode(65536);// 设置上传流区块大小,防止OutOfMemoryError

    connection.connect();
    OutputStream o = connection.getOutputStream();
    writeFileParams(o);
    writeTextParams(o);
    paramsEnd(o);
    InputStream in = connection.getInputStream();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    transfer(in, out, 1024);
    out.close();
    in.close();
    connection.disconnect();
    return out.toByteArray();
}

// 获取一个字符串表单的长度
private long getParamLength(String name, String value) throws Exception
{
    return 49 + boundary.length() + name.length() + value.getBytes().length;
}

// 获取一个文件表单的长度
private long getParamLength(String name, File value) throws Exception
{
    return 102 + boundary.length() + name.length() + value.getName().getBytes().length + value.length();
}

// 获取报文的长度
private long getLength() throws Exception
{
    long length = 0;
    for (String name : textParams.keySet())
    {
        List<String> list = textParams.get(name);
        for (String value : list)
        {
            length = length + getParamLength(name, value);
        }
    }
    for (String name : fileParams.keySet())
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值