java|Android仿Form表单以post方式提交文本和文件

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * 
 * @作者 XiaoYe yshye@live.cn 仿form表单post提交
 *
 * @修改日期 2015年12月18日下午2:40:52
 */
public class YsPostHttpUtil {
	/**
	 * 每个post参数之间的分隔。随意设定,只要不会和其他的字符串重复即可。
	 */
	private static final String BOUNDARY = "----------HV2ymHFg03ehbqgZCaKO6jyH";

	/**
	 * 
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		String filepath = "/Users/mac/Downloads/tel.png";		
		String urlStr = "url";
		Map<String, String> textMap = new HashMap<String, String>();
		textMap.put("accountcode", "wy");
		textMap.put("billid", "00E585FE1F0066C6AD5A");
		Map<String, String> fileMap = new HashMap<String, String>();
		fileMap.put("userfile", filepath);
		String ret = formUpload(urlStr, textMap, fileMap);
		System.out.println(ret);
	}

	/**
	 * 提交表单
	 * 
	 * @param urlStr
	 * @param textMap
	 * @param fileMap
	 * @return
	 * @throws Exception
	 */
	public static String formUpload(String urlStr, Map<String, String> textMap, Map<String, String> fileMap)
			throws Exception {
		// 头
		String boundary = BOUNDARY;
		// 传输内容
		StringBuffer contentBody = new StringBuffer("--" + BOUNDARY);
		// 尾
		String endBoundary = "\r\n--" + boundary + "--\r\n";

		// 2 向服务器发送post请求
		URL url = new URL(urlStr);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		// 发送POST请求必须设置如下两行
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setUseCaches(false);
		connection.setRequestMethod("POST");
		connection.setRequestProperty("Connection", "Keep-Alive");
		connection.setRequestProperty("Charset", "UTF-8");
		connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
		OutputStream out = connection.getOutputStream();
		// 2 写入内容
		// 2.1 处理普通表单域(即形如key = value对)的POST请求
		for (String key : textMap.keySet()) {
			contentBody.append("\r\n").append("Content-Disposition: form-data; name=\"").append(key + "\"")
					.append("\r\n").append("\r\n").append(textMap.get(key)).append("\r\n").append("--")
					.append(boundary);
		}
		out.write(contentBody.toString().getBytes("UTF-8"));
		// 2.2 处理文件上传
		for (String key : fileMap.keySet()) {
			contentBody = new StringBuffer();
			contentBody.append("\r\n").append("Content-Disposition:form-data; name=\"").append(key + "\"; ")
					// form中field的名称
					.append("filename=\"").append(fileMap.get(key) + "\"")
					// 上传文件的文件名,包括目录
					.append("\r\n").append("Content-Type:multipart/form-data")
					.append("\r\n\r\n");
			out.write(contentBody.toString().getBytes("utf-8"));
			// 开始真正向服务器写文件
			File file = new File(fileMap.get(key));
			DataInputStream dis = new DataInputStream(new FileInputStream(file));
			int bytes = 0;
			byte[] bufferOut = new byte[(int) file.length()];
			bytes = dis.read(bufferOut);
			out.write(bufferOut, 0, bytes);
			dis.close();
			contentBody.append(boundary);
			out.write(contentBody.toString().getBytes("utf-8"));
		}
		out.write((boundary+"--\r\n").getBytes("UTF-8"));
		// 3. 写结尾
		out.write(endBoundary.getBytes("utf-8"));
		out.flush();
		out.close();
		// 4. 获得服务器的响应结果和状态码
		int responseCode = connection.getResponseCode();
		if (responseCode == 200) {
			return changeInputStream(connection.getInputStream(), "utf-8");
		} else {
			return "";
		}
	}

	/**
	 * 获得网络返回值
	 * 
	 * @param inputStream
	 * @param encode
	 * @return
	 */
	public static String changeInputStream(InputStream inputStream, String encode) {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		int len = 0;
		String result = "";
		if (null != inputStream) {
			try {
				while ((len = inputStream.read(data)) != -1) {
					outputStream.write(data, 0, len);
				}
				result = new String(outputStream.toByteArray(), encode);
				// System.out.println(result);
			} catch (IOException e) {
                            return "";
                            //e.printStackTrace();
			}
		}
		return result;
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值