• java模拟form上传数据


    Java模拟form表单上传

    查看form表单提交的http请求为

    import java.io.*;
    import java.net.*;
    
    public class FileUpload {
        /**
        * 模拟form表单的形式 ,上传文件 以输出流的形式把文件写入到url中,然后用输入流来获取url的响应
        * @param url 请求地址 form表单url地址
        * @param filePath 文件在服务器保存路径
        * @return String url的响应信息返回值
        * @throws IOException
        */
        public String send(String url, String filePath) throws IOException {
            String result = null;
            File file = new File(filePath);
            if (!file.exists() || !file.isFile()) {
                throw new IOException("文件不存在");
            }
            /**
            * 第一部分
            */
            URL urlObj = new URL(url);
            // 连接
            HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
            /**
            * 设置关键值
            */
            con.setRequestMethod("POST"); // 请求方式
            con.setDoInput(true);
            con.setDoOutput(true);  // 当为post方式时,需要设置,因为要输入数据流
            con.setUseCaches(false); // post方式不能使用缓存
    
            // 设置请求头信息
            con.setRequestProperty("Connection", "Keep-Alive");
            con.setRequestProperty("Charset", "UTF-8");
    
            // 设置边界
            String BOUNDARY = "----------" + System.currentTimeMillis();
            con.setRequestProperty("Content-Type", "multipart/form-data; boundary="+ BOUNDARY);
    
            // 请求正文信息
            // 需要提交的文件
            StringBuilder sb = new StringBuilder();
            sb.append("--"+BOUNDARY+"
    ");
            sb.append("Content-Disposition: form-data;name="file";filename="" + file.getName() + ""
    ");
            sb.append("Content-Type:application/octet-stream
    
    ");
            byte[] head = sb.toString().getBytes("utf-8");
            // 获得输出流
            OutputStream out = new DataOutputStream(con.getOutputStream());
            // 输出表头
            out.write(head);
            // 文件正文部分
            // 把文件已流文件的方式 推入到url中
            DataInputStream in = new DataInputStream(new FileInputStream(file));
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            in.close();
            
            // 需要提交的普通表单数据
            sb = new StringBuilder();
            sb.append("
    --"+BOUNDARY+"
    ");
            sb.append("Content-Disposition: form-data;name="type"
    
    ");// 注意:在设置数据头 与 数据内容是 中间是隔了一行
            sb.append("1
    ");
            sb.append("--"+BOUNDARY+"
    ");
            sb.append("Content-Disposition: form-data;name="wxroleid"
    
    ");
            sb.append("201
    ");
            head = sb.toString().getBytes("utf-8");
            out.write(head);
            // 结尾部分
            byte[] foot = ("--" + BOUNDARY + "--
    ").getBytes("utf-8");// 定义最后数据分隔线
            out.write(foot);
            out.flush();
            out.close();
    
            StringBuffer buffer = new StringBuffer();
            BufferedReader reader = null;
            try {
                // 定义BufferedReader输入流来读取URL的响应
                reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    //System.out.println(line);
                    buffer.append(line);
                }
                if(result==null){
                    result = buffer.toString();
                }
            } catch (IOException e) {
                System.out.println("发送POST请求出现异常!" + e);
                e.printStackTrace();
                throw new IOException("数据读取异常");
            } finally {
                if(reader!=null){
                    reader.close();
                }
            }
            return result;
        }
        
        // 测试使用
        public static void main(String[] args) throws IOException {
            String filePath = "需要上传的文件路径"; // 如d:/test.pdf
            String sendUrl = "http://192.168.0.125:8080/dataProvider/uploadReport";
            String result = null;
            FileUpload fileUpload = new FileUpload();
            result = fileUpload.send(sendUrl, filePath);
            System.out.println(result);
        }
    }

    在测试的时候,如果出现http 400错误,那就是模仿form表单的格式不正确,不能解析出相关信息。 错误的地方一般在(注意换行与空行):

  • 相关阅读:
    JAVA 基本数据类型长度
    字符编码详解
    几种编码方式
    Java1.5泛型指南中文版(Java1.5 Generic Tutorial)
    java泛型小问题
    java中的equals()方法
    Java泛型中E、T、K、V等的含义
    数据库的基本操作
    Mysql数据类型简介(大概了解)
    [BZOJ 2007] 海拔
  • 原文地址:https://www.cnblogs.com/TheoryDance/p/5478743.html
Copyright © 2020-2023  润新知