本文实例讲述了golang+android基于httpurlconnection实现的文件上传功能。分享给大家供大家参考,具体如下:
这里要演示的是使用android程序作为客户端(使用httpurlconnection访问网络),golang程序作为服务器端,实现文件上传。
客户端代码:
public static string uploadfile(string uploadurl, string filepath) { log.v(tag, "url:" + uploadurl); log.v(tag, "filepath:" + filepath); string nextline = "\r\n"; string dividerstart = "--"; string boundary = "******"; try { url url = new url(uploadurl); httpurlconnection connection = (httpurlconnection) url.openconnection(); connection.setchunkedstreamingmode(1024 * 256); connection.setdoinput(true); connection.setdooutput(true); connection.setusecaches(false); connection.setrequestmethod("post"); // 设置http请求头 connection.setrequestproperty("connection", "keep-alive"); connection.setrequestproperty("charset", "utf-8"); //必须在content-type 请求头中指定分界符 connection.setrequestproperty("content-type", "multipart/form-data;boundary=" + boundary); //定义数据写入流,准备上传文件 dataoutputstream dos = new dataoutputstream(connection.getoutputstream()); dos.writebytes(dividerstart + boundary + nextline); //设置与上传文件相关的信息 dos.writebytes("content-disposition: form-data; name=\"file\"; filename=\"" + filepath.substring(filepath.lastindexof("/") + 1) + "\"" + nextline); dos.writebytes(nextline); fileinputstream fis = new fileinputstream(filepath); byte[] buffer = new byte[1024 * 32]; int count; // 读取文件内容,并写入outputstream对象 while ((count = fis.read(buffer)) != -1) { dos.write(buffer, 0, count); } fis.close(); dos.writebytes(nextline); dos.writebytes(dividerstart + boundary + dividerstart + nextline); dos.flush(); // 开始读取从服务器传过来的信息 inputstream is = connection.getinputstream(); bufferedreader br = new bufferedreader(new inputstreamreader(is, "utf-8")); string result = br.readline(); dos.close(); is.close(); connection.disconnect(); return result; } catch (ioexception e) { e.printstacktrace(); } return null; }
服务器端代码:
更多关于android相关内容感兴趣的读者可查看本站专题:《android开发入门与进阶教程》、《android调试技巧与常见问题解决方法汇总》、《android基本组件用法总结》、《android视图view技巧总结》、《android布局layout技巧总结》及《android控件用法总结》
希望本文所述对大家android程序设计有所帮助。
如对本文有疑问, 点击进行留言回复!!
LongClick原理、上下文菜单原理、EditText长按弹窗原理、WebView长按弹窗自定义、修复WebView全选重复bug ———————————————— 版权声明:本文为CSDN博主「
JobScheduler 实现 特定时间,特定条件(系统空闲,电池电量,磁盘空间 ……)下执行任务
温习Android基础知识——《第一行代码(第三版)》读书笔记 Chapter 10 Service
网友评论