HttpsURLConnection 文件上传

public synchronized String fileUpload(String url, File file) {
    String result = "";
    OutputStream out = null;
    BufferedReader in = null;
    HttpURLConnection conn = null;
    final String newLine = "\r\n";
    final String prefix = "--";
    String BOUNDARY = "-------7da2e536604c8";
    try {
        trustAllHosts();
        URL realUrl = new URL(url);
        // 通过请求地址判断请求类型(http或者是https)
        if (realUrl.getProtocol().toLowerCase().equals("https")) {
            HttpsURLConnection https = (HttpsURLConnection) realUrl.openConnection();
            https.setHostnameVerifier(DO_NOT_VERIFY);
            conn = https;
        } else {
            conn = (HttpURLConnection) realUrl.openConnection();
        }
        // 设置通用的请求属性
        conn.setRequestMethod("POST");
        // 发送POST请求必须设置如下两行
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("Charsert", "UTF-8");
        conn.setRequestProperty("Content-Type", "multipart/form-data;charset=UTF-8; boundary=" + BOUNDARY);
        // 获取URLConnection对象对应的输出流
        out = new DataOutputStream(conn.getOutputStream());
        StringBuilder sb1 = new StringBuilder();
        sb1.append(prefix);
        sb1.append(BOUNDARY);
        sb1.append(newLine);
        sb1.append("Content-Disposition:form-data;name=\"file\";filename=\"" + file.getName() + "\"" + newLine);
        sb1.append("Content-Type:application/octet-stream");
        sb1.append(newLine);
        sb1.append(newLine);
        out.write(sb1.toString().getBytes("UTF-8"));
        DataInputStream input = new DataInputStream(new FileInputStream(file));
        byte[] bufferOut = new byte[1024];
        int bytes = 0;
        while ((bytes = input.read(bufferOut)) != -1) {
            out.write(bufferOut, 0, bytes);
        }
        out.write(newLine.getBytes());

        input.close();
        byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
        // 写上结尾标识
        out.write(end_data);
        // 错误方式,这种方式容易出现乱码
        // PrintWriter out = new PrintWriter(connection.getOutputStream());
        /*out.print(a);*/
        // flush输出流的缓冲
        out.flush();
        int code = conn.getResponseCode();
        LOG.info("url:{} , httpcode:{}", url, code);
        if (code == HttpURLConnection.HTTP_OK) { // 若响应码以2开头则读取响应头总的返回信息
            // 定义BufferedReader输入流来读取URL的响应
            if (StringUtils.isNotBlank(result)) {
                result = "";
            }
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {// 使用finally块来关闭输出流、输入流
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return result;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值