今天简单说下在android中怎么使用HttpURLConnection进行文件上传
直接上代码:

 private final static String LINEND = "\r\n";    private final static String BOUNDARY = "----------fenge"; //数据分隔线    private final static String PREFIX = "--";    private final static String MUTIPART_FORMDATA = "multipart/form-data";    private final static String CONTENTTYPE = "application/octet-stream";  public static String postFile(String filePath, String url) {        try {            URL url_ = new URL(url);        //URL为http://192.168.20.223:8080/s2/20/file/groupheadupload.do?upload=filepath            HttpURLConnection conn = null;            //http开头的地址  测试服务器            conn = (HttpURLConnection) url_.openConnection();            conn.setDoInput(true);            conn.setDoOutput(true);            conn.setUseCaches(false);            conn.setConnectTimeout(1000 * 60);            conn.setReadTimeout(1000 * 60);            conn.setRequestMethod("POST");            conn.setRequestProperty("Charset", "UTF-8");            conn.setRequestProperty("User-Agent", "Android");            //这里请求头信息设为 Content-Type: multipart/form-data; boundary=----------fenge                  //boundary 为设置文件分割标志            conn.setRequestProperty("Content-Type", MUTIPART_FORMDATA + "; boundary=" + BOUNDARY);            File file = new File(filePath);            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());            StringBuilder sb = new StringBuilder();            /**             * 首先向服务器写出请求表单:             * ------------fenge             * Content-Disposition: form-data; name="upload"; filename="文件名称"\r\n             * Content-Type:application/octet-stream\r\n             * Content-Transfer-Encoding: binary\r\n\r\n             */            sb.append(PREFIX + BOUNDARY + LINEND);            sb.append("Content-Disposition: form-data; name=\"upload" + "\"; filename=\"" + file.getName() + "\"" + LINEND);            sb.append("Content-Type:" + CONTENTTYPE + LINEND);            sb.append("Content-Transfer-Encoding: binary" + LINEND + LINEND);            dos.write(sb.toString().getBytes());            /**             * 接着写文件             */            BufferedInputStream bs = new BufferedInputStream(new FileInputStream(file));            int len = 0;            byte[] buf = new byte[1024 * 1024];            while ((len = bs.read(buf)) != -1) {                dos.write(buf, 0, len);            }            bs.close();            /**             * 最后写出结束标志             * \r\n------------fenge--\r\n             */            //请求结束标志            byte[] end_data = (LINEND + PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();            dos.write(end_data);            dos.flush();            dos.close();            //上传完成 介绍返回值            /**             * 到这里算是上传完成             * 最后读取服务器的返回信息             */            int code = conn.getResponseCode();            if (code == 200) {                InputStream input = conn.getInputStream();                BufferedReader bis = new BufferedReader(new InputStreamReader(input));                StringBuilder ssb = new StringBuilder();                String line = null;                while ((line = bis.readLine()) != null) {                    ssb.append(line);                }                bis.close();                conn.disconnect();                return ssb.toString();            }        } catch (MalformedURLException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        return "";    }


这里说一下我遇到的坑:

在请求头里定义Content-Type 时,设置的boundary

在向服务器发送请求的时候,一定要在boundary的前面多加上两个减号 --

如:--boundary


在文件发送完后 要在boundary的后面多加上两个减号作为结束标志

如:--boundary--




更多相关文章

  1. Android使用HttpURLConnection和HttpClient请求服务器数据
  2. Android访问本地服务器(localhost)的解决方案
  3. android客户端程序访问服务器端webservice,几篇不错的文章!
  4. Android操作HTTP实现与服务器通信
  5. Android作为Socket服务器端
  6. Android客户端通过socket与服务器通信
  7. androdi与服务器Socket通信原理
  8. 面向UDP的Android——PC双向通信(一):实现Android客户端和PC服务器

随机推荐

  1. XX学院Android(安卓)VIP视频教程
  2. EditText常用属性
  3. 课堂小结
  4. Android(安卓)高手进阶教程(十三)之----A
  5. Android系列教程之四:Android项目的目录结
  6. android 进程与线程 - 开发文档翻译 - 线
  7. Android找到本地联络人并向其发邮件
  8. 移动平台Dialog内按键顺序研究
  9. Android(安卓)ndk开发 打包成apk后 找不
  10. android MapView 定位与Overlay onTap事