首页 > 代码库 > android post方式上传文件(模拟表单格式数据提交)
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 = http://www.mamicode.com/("\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; }}