原 Android 开发中问题收集(四):httpURLConnection Post文件上传(带参数)

一,Post请求

平时都是用第三方框架去网络请求,文件上传的,由于某种原因,现在使用原始httpURLConnection 上传文件

附一张http请求组成部分:
在这里插入图片描述

 public byte[] getToken(String baseUrl, String userName, String appId, String authToken) {
         // 参数判空
        if (baseUrl == null || baseUrl.length() == 0) {
            Log.e("TAG", "httpPost, url is null");
            return ParamIsEm.getBytes();
        }
        //请求参数拼接
        StringBuilder entry = new StringBuilder();
        if (userName != null && appId != null) {
            entry.append("userName=" + userName + "&" + "appId=" + appId + "&" + "authToken=" + authToken);

        }
        OutputStream out = null; //写
        HttpURLConnection httpURLConnection;
        try {
            httpURLConnection = Http.getHttpsURLConnection(baseUrl);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Accept", "application/json");
//            httpURLConnection.setRequestProperty("Content-type", "application/json");
            httpURLConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setConnectTimeout(30000); //30秒连接超时
            httpURLConnection.setReadTimeout(30000);    //30秒读取超时
            //传入参数
            out = httpURLConnection.getOutputStream();
            out.write(entry.toString().getBytes());
            out.flush(); //清空缓冲区,发送数据
            out.close();
            httpURLConnection.connect();
            int responseCode = httpURLConnection.getResponseCode();
            if (responseCode != 200) {
                Log.e("TAG", "httpURLConnection fail, status code = " + responseCode);
                return (NETWORKCODEERROR + responseCode).getBytes();
            }
            return readInputStream(httpURLConnection.getInputStream());
        } catch (Exception e) {
            Log.e("TAG", "httpURLConnection exception, e = " + e.getMessage());
            e.printStackTrace();
            return (NETWORKEXCEPTION + e.getMessage()).getBytes();
        }

    }
一,Post文件上传带参数

在这里插入图片描述

    private static final int TIME_OUT = 5 * 60 * 1000; // 超时时间
    String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
    String PREFIX = "--", LINE_END = "\r\n";
    String CONTENT_TYPE = "multipart/form-data"; // 内容类型
    String tail = LINE_END + PREFIX + BOUNDARY + PREFIX + LINE_END;
    String MegliveData = "megliveData";
    String CHARSET = "utf-8";
    String fileName = "face.txt";
    
    public String get(String urls, String bizToken, String appId, String data, String authToken) {
        File file = new File(Environment.getExternalStorageDirectory() + "/zhongzhua/face.txt");

        InputStream fileIs = null;
        URL url = null;
        String result;
        try {
            url = new URL(urls);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            javax.net.ssl.SSLSocketFactory ssFact = null;
            ssFact = new HNetSSLSocketFactory(null, null);
            ((HttpsURLConnection) conn).setSSLSocketFactory(ssFact);
            ((HttpsURLConnection) conn)
                    .setHostnameVerifier(new HX509HostnameVerifier());
            conn.setInstanceFollowRedirects(true);//自动处理重定向
            conn.setReadTimeout(TIME_OUT);
            conn.setConnectTimeout(TIME_OUT);
            conn.setDoInput(true); // 允许输入流
            conn.setDoOutput(true); // 允许输出流
            conn.setUseCaches(false); // 不允许使用缓存
            conn.setRequestMethod("POST"); // 请求方式
            conn.setRequestProperty("Charset", "utf-8"); // 设置编码
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE
                    + ";boundary=" + BOUNDARY);

//设置请求参数
            StringBuffer sb = new StringBuffer();
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINE_END);
            
            /**
             * 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
             * filename是文件的名字,包含后缀名的 比如:abc.png
             */
            sb.append("Content-Disposition: form-data; name=\""
                    + MegliveData + "\"; filename=\"" + fileName
                    + "\"" + LINE_END);
            sb.append("Content-Type: application/octet-stream; charset="
                    + CHARSET + LINE_END);
            sb.append(LINE_END);
//            String stringData = sb.toString();
//            int requestLength = stringData.getBytes().length + tail.length() + data.getBytes().length;
//            conn.setRequestProperty("Content-length", requestLength + "");
//            conn.setFixedLengthStreamingMode((int) requestLength);

            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            HashMap<String, String> strParams = new HashMap<>();
            strParams.put("bizToken", bizToken);
            strParams.put("authToken", authToken);
            strParams.put("appId", appId);
            /**
             * 请求体
             */
            dos.writeBytes(getStrParams(strParams).toString());
            dos.write(sb.toString().getBytes());

            fileIs = new FileInputStream(file);
            byte[] bytes = new byte[4096];
            int len = 0;
            try {
                while ((len = fileIs.read(bytes)) != -1) {
                    dos.write(bytes, 0, len);
                }
            } catch (OutOfMemoryError e) {
                result = "网络请求异常";
            }

            byte[] end_data = tail.getBytes();
            dos.write(end_data);
            dos.flush();
            int res = conn.getResponseCode();

            if (res >= HttpURLConnection.HTTP_OK && res < 300) {
                byte[] bResult = toByteArray(conn);
                result = BUtility.transcoding(new String(bResult, "UTF-8"));
            } else {
                result = "网络请求异常";
            }
            fileIs.close();
            dos.flush();
            dos.close();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return e.toString();
        }
    }
  /**
     * 对post参数进行编码处理
     */
    private StringBuilder getStrParams(Map<String, String> strParams) {
        StringBuilder strSb = new StringBuilder();
        for (Map.Entry<String, String> entry : strParams.entrySet()) {
            strSb.append(PREFIX)
                    .append(BOUNDARY)
                    .append(LINE_END)
                    .append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINE_END)
                    .append("Content-Type: text/plain; charset=" + CHARSET + LINE_END)
                    .append("Content-Transfer-Encoding: 8bit" + LINE_END)
                    .append(LINE_END)// 参数头设置完以后需要两个换行,然后才是参数内容
                    .append(entry.getValue())
                    .append(LINE_END);
        }
        return strSb;
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值