您的位置:首页 > 理论基础 > 计算机网络

Android-上传图片(-)_HttpURLConnection

2015-11-25 10:46 651 查看
继选择图片相册并通过ImageView展示在Activity中,获取到图片真实路径后(详见Android获取相册中图片的路径 4.4版本前后的变化),

将通过以下两种方式(当然了不止这两种)将获取到的图片上传到服务端,仅涉及客户端代码部分。

使用HttpURLConnection的方式模拟拼装HTTP请求

使用HttpClient(6.0已经废弃了HttpClient,但是还有有必要记录下)

本篇博客将主要记录第一种方式,下篇将记录第二种方式。

主要是模拟HTTP请求,以及流的处理。

核心代码如下,详情请移步本人GITHUB

[code]  try {
            // 实例化URL
            URL httpURL = new URL(url);
            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) httpURL.openConnection();
            /**设置connection属性 ,拼装HTTP请求协议**/
            //允许输入流 输出流  不使用缓存
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            // 以POST的方式提交
            connection.setRequestMethod("POST");
            // 设置超时时间
            connection.setReadTimeout(5 * 1000);
            connection.setConnectTimeout(5 * 1000);
            // 设置RequestProperty
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Charset", "UTF-8");
            connection.setRequestProperty("Content-Type", CONTENT_TYPE + "; boundary=" + BOUNDARY);

            // 构造DataOutputStream
            DataOutputStream ds = new DataOutputStream(connection.getOutputStream());
            /** 模拟拼装请求正文头  在浏览器开发者工具中F12网络中可以查看
             -----------------------------7df2cd15150370  (这个BOUNDARY比请求头的多--,所以定义了个prefix)
             Content-Disposition: form-data; name="file"; filename="C:\Users\Mr.Yang\Desktop\girl.jpg"
             Content-Type: image/jpeg

             -----------------------------7df2cd15150370--
             **/

            // 模拟 -----------------------------7df2cd15150370
            ds.writeBytes(PREFIX + BOUNDARY + LINE_END);
            ds.writeBytes("Content-Disposition: form-data; "
                    + "name=\"file\";filename=\"" + file.getName() + "\"" + LINE_END);
            ds.writeBytes(LINE_END);

            // 构建要上传的文件的FileInputStream
            FileInputStream fis = new FileInputStream(file);
            // 设置每次写入1024 * 4 bytes
            byte[] buffer = new byte[1024 * 4];
            int len = -1;
            // 从文件读取数据至缓冲区
            while ((len = fis.read(buffer)) != -1) {
                // 将资料写入DataOutputStream中
                ds.write(buffer, 0, len);
            }
            // 模拟换行符
            ds.writeBytes(LINE_END);
            // 模拟结尾的信息
            ds.writeBytes(PREFIX + BOUNDARY + PREFIX + LINE_END);
            // Flushes this stream to ensure all pending data is sent out to the target
            ds.flush();

            /** 接收服务端的返回信息**/
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuffer sb = new StringBuffer();

            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            LogUtils.d("服务端返回:" + sb.toString());

            // 关闭流
            if (fis != null) {
                fis.close();
            }

            if (reader != null) {
                reader.close();
            }

            if (ds != null) {
                ds.close();
            }

            // 发送消息,在主线程更新提示信息
            Message message = new Message();
            message.what = 1;
            message.obj = sb.toString();
            handler.sendMessage(message);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: