Java模拟post请求上传文件

作者 : 开心源码 本文共1751个字,预计阅读时间需要5分钟 发布时间: 2022-05-13 共275人阅读

Java模拟post请求上传文件

  • Java代码实现

    /**     * 模拟文件post上传     * @param urlStr(接口地址)     * @param formName(接口file接收名)     * @param fileName(需要上传文件的本地路径)     * @return文件上传到接口返回的结果     */public static String uploadFile(String urlStr, String  formName, String fileName) {    String baseResult = null;    try {        final String newLine = "\r\n";        final String boundaryPrefix = "--";        String BOUNDARY = "========7d4a6d158c9";// 模拟数据分隔线        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();                File file = new File(fileName);        StringBuilder sb = new StringBuilder();        sb.append(boundaryPrefix);        sb.append(BOUNDARY);        sb.append(newLine);        sb.append("Content-Disposition: form-data;name=\""+formName+"\";filename=\""+ fileName + "\"" + 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[1024];        int bytes = 0;                while ((bytes = in.read(bufferOut)) != -1) {// 每次读1KB数据,并且将文件数据写入到输出流中            out.write(bufferOut, 0, bytes);        }                out.write(newLine.getBytes());        in.close();                byte[] end_data = (newLine + boundaryPrefix + BOUNDARY                           + boundaryPrefix + newLine).getBytes();                out.write(end_data);        out.flush();        out.close();                BufferedReader reader = new BufferedReader(new InputStreamReader(            conn.getInputStream()));        String line = null;        StringBuffer strs = new StringBuffer("");        while ((line = reader.readLine()) != null) {            strs.append(line);        }        baseResult = strs;    } catch (Exception e) {        baseResult = e.getMessage();    }    return baseResult;}
说明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » Java模拟post请求上传文件

发表回复