java 文件post上传

    /**
     * 模拟文件post上传
     *
     * @param urlStr(接口地址)
     * @param formName(接口file接收名)
     * @param filePath(需要上传文件的本地路径)
     * @return文件上传到接口返回的结果
     */
    public static String uploadFile(String urlStr, String formName, String filePath) {
        long start = System.currentTimeMillis();
        File file = new File(filePath);
        if (!file.exists() || !file.canRead()) {
            throw new IllegalArgumentException("file not exists");
        }
        String baseResult = null;
        try {
            final String newLine = "\r\n";
            final String boundaryPrefix = "--";
            String BOUNDARY = "========" + System.currentTimeMillis();// 模拟数据分隔线
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");// 设置为POST请求
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setRequestProperty("connection", "Keep-Alive");// 设置请求头参数
            conn.setRequestProperty("Charsert", "UTF-8");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
            OutputStream out = conn.getOutputStream();

            StringBuilder sb = new StringBuilder();
            sb.append(boundaryPrefix);
            sb.append(BOUNDARY);
            sb.append(newLine);
            sb.append("Content-Disposition: form-data;name=\"").append(formName).append("\";filename=\"").append(file.getName()).append("\"").append(newLine);
            sb.append("Content-Type:application/octet-stream");
            sb.append(newLine);
            sb.append(newLine);

            out.write(sb.toString().getBytes());// 将参数头的数据写入到输出流中

            DataInputStream in = new DataInputStream(new FileInputStream(file));// 数据输入流,用于读取文件数据
            byte[] bufferOut = new byte[4 * 1024];
            int bytes = 0;
            final int uploadAvailable = in.available();
            int curUploadSize = 0;
            StringBuilder prgBar = new StringBuilder();
            long duration = System.currentTimeMillis();
            while ((bytes = in.read(bufferOut)) != -1) {// 每次读4KB数据,并且将文件数据写入到输出流中
                out.write(bufferOut, 0, bytes);
                curUploadSize += bytes;
                Thread.sleep(0);
                if ((System.currentTimeMillis() - duration) >= 100) {
                    prgBar.append("=");
                    String percent = String.format("%.2f", ((curUploadSize * 100.0f) / (uploadAvailable * 100.0f)) * 100);
                    String tail = "=>[" + percent + "]";
                    System.out.println(prgBar.toString() + tail);
                    duration = System.currentTimeMillis();
                }

            }
            System.out.println(prgBar.toString() + "==>[" + 100 + "]");
            System.out.println("send tcp packet data..");

            out.write(newLine.getBytes());
            in.close();

            byte[] end_data = (newLine + boundaryPrefix + BOUNDARY + boundaryPrefix + newLine).getBytes();

            out.write(end_data);
            out.flush();
            out.close();

            StringBuilder builder = new StringBuilder();
            builder.append(conn.getResponseCode()) //<===注意,实际发送请求的代码段就在这里
                    .append(" ")
                    .append(conn.getResponseMessage())
                    .append("\n");

            Map<String, List<String>> map = conn.getHeaderFields();
            for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                if (entry.getKey() == null)
                    continue;
                builder.append(entry.getKey())
                        .append(": ");

                List<String> headerValues = entry.getValue();
                Iterator<String> it = headerValues.iterator();
                if (it.hasNext()) {
                    builder.append(it.next());

                    while (it.hasNext()) {
                        builder.append(", ")
                                .append(it.next());
                    }
                }

                builder.append("\n");
            }

            System.out.println(builder);

            //读取响应体
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = null;
            StringBuilder retStr = new StringBuilder("");
            while ((line = reader.readLine()) != null) {
                retStr.append(line);
            }
            baseResult = retStr.toString();
            conn.disconnect();
        } catch (Exception e) {
            baseResult = e.getMessage();
        } finally {
            System.out.println("const_time: " + (System.currentTimeMillis() - start));
        }
        return baseResult;
    }
        String uploadFile = uploadFile(" https://m.vxiao.cn/ss", "file", "/Users/system/Downloads/com.zqzn.entranceguard_69_v2.1.2.apk");
        System.out.println(uploadFile);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值