android 向服务器上传

采用数据流的格式向服务器上传。

 

代码如下:

private void upload(String requestURL) {                          //参数requestURL 为目标url

        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(10000);
            conn.setConnectTimeout(10000);
            conn.setDoInput(true); // 允许输入流
            conn.setDoOutput(true); // 允许输出流
            conn.setUseCaches(false); // 不允许使用缓存
            conn.setRequestMethod("POST"); // 请求方式
            conn.setRequestProperty("Charset", HTTP.UTF_8); // 设置编码
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);

            //SET-COOKIE
            /**

     CookieManger cookieManger = new CookieManger();
            String cookie = cookieManger.getCookie();
            if (cookie != null && cookie.length() > 0) {
                conn.setRequestProperty("Cookie", cookie);
            }

            */

            if (bitmap != null) {          //此处以图片bitmap格式为例,别的格式一样
                /**
                 * 当文件不为空时执行上传
                 */
                DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
                StringBuffer sb = new StringBuffer();
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                /**
                 * 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
                 * filename是文件的名字,包含后缀名
                 */

                sb.append("Content-Disposition: form-data; name=\"imgFile\"; filename=\"" + System.currentTimeMillis() + ".jpg" + "\"" + LINE_END);
                sb.append("Content-Type: application/octet-stream; charset=" + HTTP.UTF_8 + LINE_END);
                sb.append(LINE_END);
                dos.write(sb.toString().getBytes());

                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                InputStream is = new ByteArrayInputStream(outputStream.toByteArray());
                outputStream.close();
                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();                     //到此向服务器发送数据完成

 

     //开始获取服务器返回数据

                InputStream input = conn.getInputStream(); 
                if (input != null) {
                    byte[] b = new byte[1024];
                    int readCount = input.read(b);
                    String result = new String(b, 0, readCount);
                    if (result != null && result.length() > 0) {
                        parseJson(result);
                    }
                    input.close();
                    Log.e("atel", "result : " + result);
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。