Android使用post方式上传图片到服务器的方法
程序员文章站
2024-02-24 20:33:28
本文实例讲述了android使用post方式上传图片到服务器的方法。分享给大家供大家参考,具体如下:
/**
* 上传文件到服务器类
*
* @au...
本文实例讲述了android使用post方式上传图片到服务器的方法。分享给大家供大家参考,具体如下:
/** * 上传文件到服务器类 * * @author tom */ public class uploadutil { private static final string tag = "uploadfile"; private static final int time_out = 10 * 1000; // 超时时间 private static final string charset = "utf-8"; // 设置编码 /** * android上传文件到服务端 * * @param file 需要上传的文件 * @param requesturl 请求的rul * @return 返回响应的内容 */ public static string uploadfile(file file, string requesturl) { string result = null; string boundary = uuid.randomuuid().tostring(); // 边界标识 随机生成 string prefix = "--", line_end = "\r\n"; string content_type = "multipart/form-data"; // 内容类型 try { url url = new url(requesturl); httpurlconnection conn = (httpurlconnection) url.openconnection(); conn.setreadtimeout(time_out); conn.setconnecttimeout(time_out); conn.setdoinput(true); // 允许输入流 conn.setdooutput(true); // 允许输出流 conn.setusecaches(false); // 不允许使用缓存 conn.setrequestmethod("post"); // 请求方式 conn.setrequestproperty("charset", charset); // 设置编码 conn.setrequestproperty("connection", "keep-alive"); conn.setrequestproperty("content-type", content_type + ";boundary=" + boundary); if (file != null) { /** * 当文件不为空,把文件包装并且上传 */ dataoutputstream dos = new dataoutputstream(conn.getoutputstream()); stringbuffer sb = new stringbuffer(); sb.append(prefix); sb.append(boundary); sb.append(line_end); /** * 这里重点注意: name里面的值为服务端需要key 只有这个key 才可以得到对应的文件 * filename是文件的名字,包含后缀名的 比如:abc.png */ sb.append("content-disposition: form-data; name=\"uploadfile\"; filename=\"" + file.getname() + "\"" + line_end); sb.append("content-type: application/octet-stream; charset=" + charset + line_end); sb.append(line_end); dos.write(sb.tostring().getbytes()); inputstream is = new fileinputstream(file); byte[] bytes = new byte[1024]; int len = 0; while ((len = is.read(bytes)) != -1) { dos.write(bytes, 0, len); } is.close(); dos.write(line_end.getbytes()); byte[] end_data = (prefix + boundary + prefix + line_end).getbytes(); dos.write(end_data); dos.flush(); /** * 获取响应码 200=成功 当响应成功,获取响应的流 */ int res = conn.getresponsecode(); log.e(tag, "response code:" + res); // if(res==200) // { log.e(tag, "request success"); inputstream input = conn.getinputstream(); stringbuffer sb1 = new stringbuffer(); int ss; while ((ss = input.read()) != -1) { sb1.append((char) ss); } result = sb1.tostring(); log.e(tag, "result : " + result); // } // else{ // log.e(tag, "request error"); // } } } catch (malformedurlexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } return result; } /** * 通过拼接的方式构造请求内容,实现参数传输以及文件传输 * * @param url service net address * @param params text content * @param files pictures * @return string result of service response * @throws ioexception */ public static string post(string url, 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(url); httpurlconnection conn = (httpurlconnection) uri.openconnection(); conn.setreadtimeout(10 * 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) 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=\"uploadfile\"; filename=\"" + file.getvalue().getname() + "\"" + 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 = conn.getinputstream(); stringbuilder sb2 = new stringbuilder(); if (res == 200) { int ch; while ((ch = in.read()) != -1) { sb2.append((char) ch); } } outstream.close(); conn.disconnect(); return sb2.tostring(); } }
示例调用第二种方式上传:
final map<string, string> params = new hashmap<string, string>(); params.put("send_userid", string.valueof(id)); params.put("send_email", address); params.put("send_name", name); params.put("receive_email", emails); final map<string, file> files = new hashmap<string, file>(); files.put("uploadfile", file); final string request = uploadutil.post(requesturl, params, files);
更多关于android相关内容感兴趣的读者可查看本站专题:《android调试技巧与常见问题解决方法汇总》、《android开发入门与进阶教程》、《android多媒体操作技巧汇总(音频,视频,录音等)》、《android基本组件用法总结》、《android视图view技巧总结》、《android布局layout技巧总结》及《android控件用法总结》
希望本文所述对大家android程序设计有所帮助。