介绍
这篇文章主要介绍Android如何实现多参数文件和数据上,传文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
具体内容如下
上代码:
/* * ,*可传入多张图片和参数 *大敌; ,* @param actionUrl ,*,,发送地址 ,* @param 参数 ,*,,文本参数 ,* @param 文件 ,*,,文件参数 ,* @return ,* @throws IOException ,*/,public static  String mulpost (String actionUrl, Map<字符串,String>,参数, ,Map<字符串,File>,文件),throws IOException { ,String result =,““ , ,String BOUNDARY =, java.util.UUID.randomUUID () .toString (); ,String PREFIX =,,,,,, LINEND =,“\ r \ n"; ,String MULTIPART_FROM_DATA =,“多部分/form-data"; ,String CHARSET =,“UTF-8"; ,URL uri =, new URL (actionUrl); ,HttpURLConnection conn =, (HttpURLConnection), uri.openConnection (); ,conn.setReadTimeout (5, *, 1000); ,conn.setDoInput(真正);//,允许输入 ,conn.setDoOutput(真正);//,允许输出 ,conn.setUseCaches(假); ,conn.setRequestMethod (“POST");,//,发布方式 ,conn.setRequestProperty (“connection",,“keep-alive"); ,conn.setRequestProperty (“Charsert",,“UTF-8"); ,conn.setRequestProperty (“Content-Type", MULTIPART_FROM_DATA ,+“;边界=?+,边界); , ,//首先组拼文本类型的参数 ,StringBuilder sb =, new StringBuilder (); ,for (Map.Entry<字符串,String>, entry :, params.entrySet ()), { ,sb.append(前缀); ,sb.append(边界); ,sb.append (LINEND); ,sb.append(“附加项:格式;,名字=\”;“ +,才能entry.getKey (), +,“\““, +, LINEND); ,sb.append(“内容类型:文本/平原;,charset=? +, CHARSET +, LINEND); ,sb.append (“Content-Transfer-Encoding: 8 bit", +, 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) ,for (Map.Entry<字符串,File>, file :, files.entrySet ()), { ,StringBuilder sb1 =, new StringBuilder (); ,sb1.append(前缀); ,sb1.append(边界); ,sb1.append (LINEND); ,sb1.append(“附加项:格式;,name=\“文件\“;;,文件名=\”;“ +,才能file.getKey (), +,“\““, +, LINEND); ,sb1.append(“内容类型:应用程序/八进制;,charset=? +,才能CHARSET +, LINEND); ,sb1.append (LINEND); ,outStream.write (sb1.toString () .getBytes ()); ,InputStream is =, new FileInputStream (file.getValue ()); ,byte [], buffer =, new 字节[1024]; ,int len =, 0; ,while ((len =, is.read(缓冲)),!=,1),{ outStream.write才能(缓冲,0,,len); ,} , ,is.close (); ,outStream.write (LINEND.getBytes ()); ,} , ,//请求结束标志 ,byte [], end_data =,(时间+ PREFIX BOUNDARY +, PREFIX +, LINEND) .getBytes (); ,outStream.write (end_data); ,outStream.flush (); , ,InputStream is =, conn.getInputStream (); ,InputStreamReader isr =, new InputStreamReader (,,“utf-8"); ,BufferedReader br =, new BufferedReader (isr);=,,result  br.readLine (); ,outStream.close (); ,conn.disconnect (); ,return 结果; 以前,}>方法就是这样的。
使用时可封装在自己的类里直接调用即可,记得加网络访问和读取系统文件的权限哦。
& lt; uses-permission android: name=癮ndroid.permission.INTERNET",/比; & lt; uses-permission  android: name=癮ndroid.permission.READ_EXTERNAL_STORAGE",/在由于上传是耗时操作,必须得要弄在另一个线程中调用才可以。
以上是“android如何实现多参数文件和数据上传”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注行业资讯频道!
Android如何实现多参数文件和数据上传