Android-上传图片(-)_HttpURLConnection

继选择图片相册并通过ImageView展示在Activity中,获取到图片真实路径后(详见Android获取相册中图片的路径 4.4版本前后的变化),
将通过以下两种方式(当然了不止这两种)将获取到的图片上传到服务端,仅涉及客户端代码部分。

  1. 使用HttpURLConnection的方式模拟拼装HTTP请求
  2. 使用HttpClient(6.0已经废弃了HttpClient,但是还有有必要记录下)

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

主要是模拟HTTP请求,以及流的处理。
核心代码如下,详情请移步本人GITHUB

  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();
        }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小小工匠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值