/**
* 通过拼接的方式构造请求内容,实现参数传输以及文件传输
* @param actionUrl
* @param params
* @param files
* @return
* @throws IOException
*/
public static String post(String actionUrl, Map<String, String> params,
Map<String, File> files) throws IOException {

String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--" , LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";

URL uri = new URL(actionUrl);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setReadTimeout(5 * 1000); // 缓存的最长时间
conn.setDoInput(true);// 允许输入
conn.setDoOutput(true);// 允许输出
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);

// 首先组拼文本类型的参数
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
sb.append("Content-Type: text/plain; charset=" + CHARSET+LINEND);
sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
}

DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(sb.toString().getBytes());
// 发送文件数据
if(files!=null){
int i = 0;
for (Map.Entry<String, File> file: files.entrySet()) {
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
sb1.append("Content-Disposition: form-data; name=\"file"+(i++)+"\"; filename=\""+file.getKey()+"\""+LINEND);
sb1.append("Content-Type: application/octet-stream; charset="+CHARSET+LINEND);
sb1.append(LINEND);
outStream.write(sb1.toString().getBytes());

InputStream is = new FileInputStream(file.getValue());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}

is.close();
outStream.write(LINEND.getBytes());
}
}

//请求结束标志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();

//得到响应码
int res = conn.getResponseCode();
InputStream in = null;
if (res == 200) {
in = conn.getInputStream();
int ch;
StringBuilder sb2 = new StringBuilder();
while ((ch = in.read()) != -1) {
sb2.append((char) ch);
}
}
return in == null ? null : in.toString();
}



最简单的PHP测试代码:

if($_FILES){
foreach($_FILES as $v){
copy($v[tmp_name], $v[name]);
}
}



参考自 Android中发送Http请求实例(包括文件上传、servlet接收) ,修复了几个问题:
1 多文件上传 file"+(i++)+"
2 返回的错误

另外还可以看看这个(我没测试) android 文件上传的类--完整 可以直接被调用的

这有一个从协议上分析的,比较牛叉:Android下的应用编程——用HTTP协议实现文件上传功能

原创内容如转载请注明:来自 阿权的书房 <script> //&lt;![cdata[ document.write(&quot;&lt;br /&gt;本帖地址:&lt;a href=\&quot;&quot;+window.location+&quot;\&quot;&gt;&quot;+window.location+&quot;&lt;/a&gt;&quot;); //]]&gt; </script>
本帖地址:http://www.aslibra.com/blog/post/android-upload-files-to-server.php

http 上传文件的方法

  1. 1./**
  2. 2.*
  3. 3.*sendMultipartDataToHttpServer
  4. 4.*使用post方法请求web服务器,并且当表单数据为:multipart/form-data格式。http请求使用{@link#HTTP_ENCODING}编码<br/>
  5. 5.*返回json数据,支持文件名中文上传和多文件上传,不支持断点上传,要正确编码服务端返回{@link#HTTP_ENCODING}编码<br/>
  6. 6.*@paramurl
  7. 7.*@paramfiles文件表单域
  8. 8.*@paramfields非文件表单域
  9. 9.*@returnJSONObject
  10. 10.*@throwsException
  11. 11.*@exception
  12. 12.*@since1.0.0
  13. 13.*/
  14. 14.publicstaticJSONObjectsendMultipartDataToHttpServer(URLurl,
  15. 15.finalMap<String,File>files,finalMap<String,String>fields,
  16. 16.finalUsernamePasswordCredentialscredentials)throwsIOException,JSONException,Exception{
  17. 17.URLmyurl=null;
  18. 18.StringqueryString="";
  19. 19.//其他的表单域
  20. 20.if(fields!=null){
  21. 21.for(Map.Entry<String,String>entry:fields.entrySet()){
  22. 22.queryString+="&"+URLEncoder.encode(entry.getKey(),HTTP_ENCODING)+"="
  23. 23.+URLEncoder.encode(entry.getValue(),HTTP_ENCODING);
  24. 24.}
  25. 25.}
  26. 26.if(!queryString.equals("")){
  27. 27.queryString=queryString.replaceFirst("&","?");
  28. 28.}else{
  29. 29.}
  30. 30.
  31. 31.myurl=newURL(url.getProtocol(),url.getHost(),url.getPort(),url.getPath()
  32. 32.+queryString);
  33. 33.HttpURLConnectionconn=(HttpURLConnection)myurl.openConnection();
  34. 34.conn.setConnectTimeout(UPLOAD_REQUEST_TIMEOUT);
  35. 35.conn.setRequestMethod(HTTP_METHOD.POST.toString());
  36. 36.conn.setDoInput(true);
  37. 37.conn.setDoOutput(true);
  38. 38.conn.setUseCaches(false);
  39. 39.
  40. 40.Stringboundary="laohuidi_"+java.util.UUID.randomUUID().toString()
  41. 41.+"_laohuidi";
  42. 42.conn.setRequestProperty(
  43. 43."Accept",
  44. 44."image/gif,image/x-xbitmap,image/jpeg,image/pjpeg,application/vnd.ms-excel,application/vnd.ms-powerpoint,application/msword,application/x-shockwave-flash,application/x-quickviewplus,*/*");
  45. 45.conn.setRequestProperty("keep-alive","300");
  46. 46.conn.setRequestProperty(
  47. 47."user-agent",
  48. 48."Mozilla/5.0(Windows;U;WindowsNT5.2;zh-CN;rv:1.9.1.6)Gecko/20091201Firefox/3.5.6GTB6");
  49. 49.conn.setRequestProperty("accept-language","zh-cn,zh;q=0.5");
  50. 50.conn.setRequestProperty("Connection","Keep-Alive");
  51. 51.conn.setRequestProperty("Content-Type","multipart/form-data;boundary="+boundary);
  52. 52.
  53. 53.DataOutputStreamdos=newDataOutputStream(conn.getOutputStream());
  54. 54.//乱码问题可以试下PrintWriterout=newPrintWriter(new
  55. 55.//OutputStreamWriter(connection.getOutputStream(),"utf-8"));
  56. 56.dos=newDataOutputStream(conn.getOutputStream());
  57. 57.intbytesRead,bytesAvailable,bufferSize;
  58. 58.byte[]buffer;
  59. 59.intmaxBufferSize=IO_BUFFER_SIZE;
  60. 60.Stringtem="";
  61. 61.if(files!=null)
  62. 62.for(Map.Entry<String,File>entry:files.entrySet()){
  63. 63.//分隔符开头
  64. 64.dos.writeBytes(TWO_HYPHENS+boundary+LINEND);
  65. 65.//createabufferofmaximumsize
  66. 66.FileInputStreamfileInputStream=newFileInputStream(entry.getValue());
  67. 67.bytesAvailable=fileInputStream.available();
  68. 68.bufferSize=Math.min(bytesAvailable,maxBufferSize);
  69. 69.buffer=newbyte[bufferSize];
  70. 70.//readfileandwriteitintoform...
  71. 71.bytesRead=fileInputStream.read(buffer,0,bufferSize);
  72. 72.tem=entry.getValue().getName();
  73. 73.dos.writeBytes("Content-Disposition:form-data;name=\""+entry.getKey()+"\";"+"filename=\"");
  74. 74.dos.writeUTF(tem);//中文的文件名使用这里
  75. 75.dos.writeBytes("\""+LINEND);
  76. 76.dos.writeBytes("Content-Type:image/jpg"+LINEND+LINEND);//类型的判断暂时不处理
  77. 77.while(bytesRead>0){
  78. 78.dos.write(buffer,0,bufferSize);
  79. 79.bytesAvailable=fileInputStream.available();
  80. 80.bufferSize=Math.min(bytesAvailable,maxBufferSize);
  81. 81.bytesRead=fileInputStream.read(buffer,0,bufferSize);
  82. 82.}
  83. 83.//closestreams
  84. 84.fileInputStream.close();
  85. 85.dos.writeBytes(LINEND);
  86. 86.}
  87. 87.//http结束符
  88. 88.dos.writeBytes(TWO_HYPHENS+boundary+TWO_HYPHENS);
  89. 89.dos.writeBytes(LINEND);
  90. 90.
  91. 91.dos.flush();
  92. 92.dos.close();
  93. 93.//返回类型
  94. 94.StringresponseType=conn.getHeaderField("Content-Type");
  95. 95.//正常返回而且必须为json类型
  96. 96.if(conn.getResponseCode()==HttpURLConnection.HTTP_OK
  97. 97.&&responseType!=null
  98. 98.&&responseType.indexOf(HTTP_JSON_TYPE)>=0){
  99. 99.responseType=(convertStreamToString(conn.getInputStream()));
  100. 100.
  101. 101.}else{
  102. 102.responseType="{}";
  103. 103.}
  104. 104.try{conn.disconnect();}catch(Exceptione){}
  105. 105.returnnewJSONObject(responseType);
  106. 106.}

更多相关文章

  1. wzplayer for android V1.5.3 (新增YUV文件播放)
  2. Android解析自定义xml文件(方案一)
  3. Android客制化------开机拷贝文件到内置存储
  4. android log日志文件输出
  5. android按行读取文件内容的几个方法
  6. android 文件 修改权限
  7. android 打开不同文件工具类
  8. 使用命令行ls命令的Android文件浏览控件,适合于root过的设备,可以

随机推荐

  1. Android(安卓)2.1 源码结构分析 转载
  2. android 出错信息为:Class 'Anonymous cla
  3. Android(安卓)对话框【Dialog】去除白色
  4. Android(安卓)Q fastboot刷GSI(MTK)
  5. Android(安卓)网络连接处理 学习笔记
  6. Android(安卓)复盘——你真的了解 setCon
  7. 对android 项目工程 sdk编译版本、build
  8. Android中调试获取Log
  9. android学习——activity的生命周期
  10. Android(安卓)程序获取、设置铃声、音量