android post方式上传文件(模拟表单格式数据提交)

表单提交内容为:

POST /upload.php?zp_id=ab46ca6d703e3a1580c1c9b8b3a8fb39 HTTP/1.1
Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*
Referer: http://campus.eastmoney.com/upload/uploadf.php?zp_id=ab46ca6d703e3a1580c1c9b8b3a8fb39
Accept-Language: zh-cn
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)
Content-Type: multipart/form-data; boundary=---------------------------7de8c1a80910
Accept-Encoding: gzip, deflate
Host: campus.eastmoney.com
Content-Length: 8636
Connection: Keep-Alive
Cache-Control: no-cache
Cookie: emstat_bc_emcount=7843405732305291404; emstat_ss_emcount=104_1395241887_3077552069; zp_id=ab46ca6d703e3a1580c1c9b8b3a8fb39; zp_tag=%C8%CB%CA%C2%D6%FA%C0%ED%A3%A8%C8%CB%C1%A6%D7%CA%D4%B4%B2%BF%A3%A9; PHPSESSID=e4820e25c1ced88e0e677ed9610f3f56

-----------------------------7de8c1a80910
Content-Disposition: form-data; name="__VIEWSTATE"

-----------------------------7de8c1a80910
Content-Disposition: form-data; name="txtFileSer"

-----------------------------7de8c1a80910
Content-Disposition: form-data; name="txtSeqID"

94564504-c3bd-44c1-8048-e1195f701c9b
-----------------------------7de8c1a80910
Content-Disposition: form-data; name="txtAlias"

-----------------------------7de8c1a80910
Content-Disposition: form-data; name="txtSourceID"

8619075e-952c-45d5-90e7-43d80e1e7f40
-----------------------------7de8c1a80910
Content-Disposition: form-data; name="txtCname"

-----------------------------7de8c1a80910
Content-Disposition: form-data; name="txtUpLoad"; filename="ss.jpg"
Content-Type: image/pjpeg

籿湈x=*旫?;?欋芳管搪O*kbpU#m噡

-----------------------------7de8c1a80910
Content-Disposition: form-data; name="btnUpload"

上传
-----------------------------7de8c1a80910--

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.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;

import com.eastmoney.util.FileUtil;

public class HttpAssistant implements Runnable {
	public static final int REQUEST_ERROR = 0xFFF;
	public static final int URL_MARLFORMED_ERROR = 0xFFE;
	public static final int IO_EXCEPTION_REEOR = 0xFFD;
	public static final int RESPONSE_SUCCESS = 0xFFC;

	final int CONNECT_TIME_OUT = 10000;
	final int READ_TIME_OUT = 10000;
	String requestString;
	HttpResponseCallback mCallback;
	RequestType type;
	HashMap<String, String> params;

	/**
	 * @param requestString
	 *            请求字串
	 * @param callback
	 *            请求结果回调
	 * @param type
	 *            请求类型(GET/POST)
	 * @param params
	 *            post请求参数
	 */
	public HttpAssistant(String requestString, HttpResponseCallback callback,
			RequestType type, HashMap<String, String> params) {
		this.requestString = requestString;
		this.mCallback = callback;
		this.type = type;
		this.params = params;
	}

	@Override
	public void run() {
		if (type == null) {
			throw new IllegalArgumentException(
					"NetworkRequest must specify a request type");
		}
		StringBuilder sb = new StringBuilder();
		HttpURLConnection conn = null;
		if (type == RequestType.GET || type == RequestType.GET_THUMBNAIL
				|| type == RequestType.GET_AUDIO
				|| type == RequestType.GET_IMAGE) {
			// GET请求
			try {
				URL url = new URL(requestString);
				conn = (HttpURLConnection) url.openConnection();
				conn.setConnectTimeout(CONNECT_TIME_OUT);
				conn.setReadTimeout(READ_TIME_OUT);
				conn.connect();
				InputStream is = conn.getInputStream();
				if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
					if (mCallback != null) {
						mCallback.onResponse(REQUEST_ERROR, null);
					}
					conn.disconnect();
					return;
				}
				if (type == RequestType.GET) {
					BufferedReader br = new BufferedReader(
							new InputStreamReader(is));
					String line = null;
					sb.setLength(0);
					while ((line = br.readLine()) != null) {
						sb.append(line);
					}
					if (mCallback != null) {
						mCallback.onResponse(RESPONSE_SUCCESS, sb.toString());
					}
				} else {
					File file = null;
					if (type == RequestType.GET_THUMBNAIL) {
						file = FileUtil.createCacheFile(
								String.valueOf(requestString.hashCode()),
								FileUtil.Type.THUMBNAIL);
					} else if (type == RequestType.GET_IMAGE) {
						file = FileUtil.createCacheFile(
								String.valueOf(requestString.hashCode()),
								FileUtil.Type.IMAGE);
					} else if (type == RequestType.GET_AUDIO) {
						file = FileUtil.createCacheFile(
								String.valueOf(requestString.hashCode()),
								FileUtil.Type.AUDIO);
					}
					if (file == null) {
						if (mCallback != null) {
							mCallback.onResponse(IO_EXCEPTION_REEOR, null);
						}
						return;
					}
					FileOutputStream fos = new FileOutputStream(file);
					byte[] buffer = new byte[1024];
					int length = 0;
					while ((length = is.read(buffer)) != -1) {
						fos.write(buffer, 0, length);
					}
					fos.flush();
					fos.close();
					if (mCallback != null) {
						mCallback.onResponse(RESPONSE_SUCCESS, file);
					}
					buffer = null;
					System.gc();
				}
				conn.disconnect();
				return;
			} catch (MalformedURLException e) {
				if (mCallback != null) {
					mCallback.onResponse(URL_MARLFORMED_ERROR, null);
				}
			} catch (IOException e) {
				if (mCallback != null) {
					mCallback.onResponse(IO_EXCEPTION_REEOR, null);
				}
			} finally {
				if (conn != null) {
					conn.disconnect();
				}
			}
		} else if (type == RequestType.POST_IMAGE
				|| type == RequestType.POST_AUDIO) {
			if (params == null) {
				throw new IllegalArgumentException(
						"Post request must specify arguments");
			}
			// 数据分割线
			String BOUNDARY = "---------------------------7de8c1a80910";
			// POST请求
			try {
				URL url = new URL(requestString);
				conn = (HttpURLConnection) url.openConnection();
				conn.setConnectTimeout(CONNECT_TIME_OUT);
				conn.setDoOutput(true);
				conn.setDoInput(true);
				conn.setUseCaches(false);
				conn.setReadTimeout(READ_TIME_OUT);
				conn.setRequestMethod("POST");
				conn.setRequestProperty("Connection", "Keep-Alive");
				conn.setRequestProperty("Charset", "UTF-8");
				conn.setRequestProperty(
						"User-Agent",
						"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)");
				conn.setRequestProperty("Content-Type",
						"multipart/form-data; boundary=" + BOUNDARY);
				// 末尾数据分隔符
				byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
				// 数据输出流
				DataOutputStream dos = new DataOutputStream(
						conn.getOutputStream());
				// 构建post数据
				sb.setLength(0);
				Iterator<String> i = params.keySet().iterator();
				while (i.hasNext()) {
					String key = i.next();
					if (!key.equals("txtUpLoad")) {
						// 向输出流中填写普通文本数据
						sb.append("\r\n\r\n\r\n--" + BOUNDARY + "\r\n");
						sb.append("Content-Disposition: form-data; name=\""
								+ key + "\"" + "\r\n\r\n");
						sb.append(params.get(key) + "\r\n");
						dos.write(sb.toString().getBytes());
						sb.setLength(0);
					} else {
						// 向输出流中填写上传的文件数据
						sb.append("\r\n\r\n--" + BOUNDARY + "\r\n");
						sb.append("Content-Disposition: form-data; name=\"txtUpLoad\"; filename=\""
								+ params.get("txtUpLoad") + "\"" + "\r\n");
						if (type == RequestType.POST_IMAGE) {
							sb.append("Content-Type: image/*\r\n\r\n");
						} else {
							sb.append("Content-Type: audio/*\r\n\r\n");
						}
						dos.write(sb.toString().getBytes());
						sb.setLength(0);
						// 传输文件数据
						FileInputStream fis = new FileInputStream(new File(
								params.get("txtUpLoad")));
						byte[] buffer = new byte[1024];
						int length = 0;
						while ((length = fis.read(buffer)) != -1) {
							dos.write(buffer, 0, length);
						}
						fis.close();
					}
				}
				dos.write(endData);
				// 刷新输出流
				dos.flush();
				dos.close();
				// 获取返回数据
				InputStream is = conn.getInputStream();
				if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
					if (mCallback != null) {
						mCallback.onResponse(REQUEST_ERROR, null);
					}
					conn.disconnect();
					return;
				}
				sb.setLength(0);
				BufferedReader br = new BufferedReader(
						new InputStreamReader(is));
				String line = null;
				while ((line = br.readLine()) != null) {
					sb.append(line);
				}
				if (mCallback != null) {
					mCallback.onResponse(RESPONSE_SUCCESS, sb.toString());
				}
				conn.disconnect();
			} catch (MalformedURLException e) {
				if (mCallback != null) {
					mCallback.onResponse(URL_MARLFORMED_ERROR, null);
				}
			} catch (IOException e) {
				if (mCallback != null) {
					mCallback.onResponse(IO_EXCEPTION_REEOR, null);
				}
			} finally {
				if (conn != null) {
					conn.disconnect();
				}
			}
		}
	}

	/** 设置网络请求回调. */
	public void setCallback(HttpResponseCallback callback) {
		this.mCallback = callback;
	}

	/** 网络请求回调接口. */
	public static interface HttpResponseCallback {
		public void onResponse(int responseCode, Object responseObject);
	}

	public static enum RequestType {
		/** 一般get请求,返回数据为字符串 */
		GET,
		/** 获取头像缩略图. */
		GET_THUMBNAIL,
		/** 获取图片文件. */
		GET_IMAGE,
		/** 获取音频文件 */
		GET_AUDIO,
		/** post请求,上传数据为image */
		POST_IMAGE,
		/** post请求,上传数据为audio */
		POST_AUDIO;
	}
}

  

android post方式上传文件(模拟表单格式数据提交),布布扣,bubuko.com

时间: 2024-10-12 23:23:31

android post方式上传文件(模拟表单格式数据提交)的相关文章

? 为什么上传文件的表单里要加个属性enctype----摘录

上传文件的表单中<form>要加属性enctype="multipart/form-data",很多人只是死记硬背知道上传表单要这么写,知其然而不知其所以然.那到底为什么要添加这个属性呢?它是什么意思呢?它又有什么其他可选值呢? 其实form表单在你不写enctype属性时,也默认为其添加了enctype属性值,默认值是enctype="application/x-www-form-urlencoded".这个属性管理的是表单的MIME编码,共有三个值可

上传文件form表单enctype=&quot;multipart/form-data&quot;传值解决办法(代原代码)

最近做的一个项目里遇到一个问 题,就是如何在上传文件的表单里传递其它的变量,因为一但form表单用了enctype="multipart/form-data"类型后,所有的值 都是以二进制进行传递的,所以当我们想取出这个表单里传递过来的其它变量的时候,就会遇到一个问题,那就是用request取不到传递过来的变量.在网上 找了很多资料,也都是大至说一下,在这里我就借花献佛发个完整的原代码解决这个问题!!! 工程目录如下: 两个jar可以去apache上下载: http://commons

android 上传文件(表单),表单填写格式分析

原文地址:http://blog.sina.com.cn/s/blog_68494364010116gk.html 在Android的客户端编程中(特别是SNS 类型的客户端),经常需要实现注册功能Activity,要用户输入用户名,密码,邮箱,照片后注册.但这时就有一个问题,在HTML中用form表单就 能实现如上的注册表单,需要的信息会自动封装为完整的HTTP协议,但在Android中如何把这些参数和需要上传的文件封装为HTTP协议呢? 我们可以先做个试验,看一下form表单到底封装了什么样

为什么上传文件的表单里要加个属性enctype

上传文件的表单中<form>要加属性enctype="multipart/form-data",很多人只是死记硬背知道上传表单要这么写,知其然而不知其所以然.那到底为什么要添加这个属性呢?它是什么意思呢?它又有什么其他可选值呢? 其实form表单在你不写enctype属性时,也默认为其添加了enctype属性值,默认值是enctype="application/x-www-form-urlencoded".这个属性管理的是表单的MIME编码,共有三个值可

为什么上传文件的表单里面要加一个属性ENCTYPE=MULTIPART/FORM-DATA?

首先知道enctype这个属性管理的是表单的MIME编码.共有三个值可选:1.application/x-www-form-urlencoded2.multipart/form-data3.text/plain其中application/x-www-form-urlencoded是默认值,作用是设置表单传输的编码.例如我们在AJAX中见过xmlHttp.setRequestHeader("Content-Type","application/x-www-form- urlen

上传文件的表单

1.使用Apache 的 Commons FileUpload FileUpload下载地址: http://commons.apache.org/fileupload/ 下载:commons-fileupload-1.2.2-bin.zip    得到:commons-fileupload-1.2.2.jar http://commons.apache.org/io/ 下载:commons-io-1.4-bin.zip       得到:commons-io-1.4.jar 2.web.xml

servlet文件上传2——复合表单提交(数据获取和文件上传)

上传文件时表单enctype属性必须要更改为<enctype='multipart/form-data'>:采用post提交表单,元素需要有name属性: 利用第三方jar包(commons-fileupload-1.2.1.jar   commons-io-1.3.2.jar )进行普通数据获取和文件上传:普通文本需要用getString("编码格式")方法获取,否则汉字会出现乱码,最开始我一直用的getString()获取,发现传到数据的数据全是乱码,查看流浪器的里面的

Android必知必会-使用okhttp的PUT方式上传文件

背景 公司的文件上传接口使用PUT协议,之前一直用的都是老项目中的上传类,现在项目中使用了okhttp网络库,就查了下资料,在这里分享一下. 代码实现 /** * @param mediaType MediaType * @param uploadUrl put请求地址 * @param localPath 本地文件路径 * @return 响应的结果 和 HTTP status code * @throws IOException */ public String put(MediaType

通过Ajax方式上传文件,使用FormData进行Ajax请求

通过传统的form表单提交的方式上传文件: 1 2 3 4 5 6 7 8 9 <form id= "uploadForm" action= "http://localhost:8080/cfJAX_RS/rest/file/upload" method= "post" enctype ="multipart/form-data">       <h1 >测试通过Rest接口上传文件 </h1&g