js 里的 XMLHttpRequest 用 java 中的 HttpURLConnection 怎么写?

oldfeel 发布于 2016/06/17 19:38
阅读 383
收藏 1

js 代码如下:

var xhr = new XMLHttpRequest();
			xhr.onreadystatechange = getAudioResult; //设置回调函数
			xhr.open("POST", "http://www.exampole.com/svc/topic?type=mediaUpload", true);

			var formData = new FormData();
			formData.append("file", audioFile);
			xhr.send(formData);



加载中
0
空杯子
空杯子

推荐:HttpClient

不过应用要是没那么频繁的话,可以参考下面的代码:

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.exampole.com/svc/topic?type=mediaUpload";
		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())
		{
			List<File> list = fileParams.get(name);
			for (File value : list)
			{
				length = length + getParamLength(name, value);
			}
		}
		length = length + boundary.length() + 8;
		return length;
	}

	// 普通字符串数据
	private void writeTextParams(OutputStream o) throws Exception
	{
		for (String name : textParams.keySet())
		{
			List<String> list = textParams.get(name);
			for (String value : list)
			{
				o.write(new StringBuffer().append("--").append(boundary).append("\r\nContent-Disposition: form-data; name=\"").append(name).append("\"\r\n\r\n").append(value).append("\r\n").toString()
						.getBytes());
			}
		}
	}

	// 文件数据
	private void writeFileParams(OutputStream o) throws Exception
	{
		for (String name : fileParams.keySet())
		{
			List<File> list = fileParams.get(name);
			for (File value : list)
			{
				o.write(new StringBuffer().append("--").append(boundary).append("\r\nContent-Disposition: form-data; name=\"").append(name).append("\"; filename=\"").append(value.getName())
						.append("\"\r\nContent-Type: application/octet-stream\r\n\r\n").toString().getBytes());
				writeFile(value, o);
				o.write("\r\n".getBytes());
			}
		}
	}

	// 输出文件
	private void writeFile(File f, OutputStream o) throws Exception
	{
		InputStream in = new FileInputStream(f);
		transfer(in, o);
		in.close();
	}

	// 添加结尾数据
	private void paramsEnd(OutputStream o) throws Exception
	{
		o.write(new StringBuffer().append("--").append(boundary).append("--\r\n\r\n").toString().getBytes());
	}

	// 数据传输
	public static void transfer(InputStream in, OutputStream out) throws Exception
	{
		transfer(in, out, 65536);
	}

	// 数据传输,指定缓冲区大小
	public static void transfer(InputStream in, OutputStream out, int bufSize) throws Exception
	{
		byte[] b = new byte[bufSize];
		int n;
		while ((n = in.read(b)) != -1)
		{
			out.write(b, 0, n);
		}
		b = null;
	}
}



返回顶部
顶部