Java Form表单内多个文件提交请求(使用CloseableHttpClient或OkHttpClient)


CloseableHttpClient

    //实际情况建议使用单例client
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost("http://test.com");

        // 需要上传的excel,这里是直接使用poi生成excel
        ContentBody excel = newExcelContent("test.xls");
        // form内容
        HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("param1", new StringBody("value1", ContentType.TEXT_PLAIN))
                .addPart("param2", new StringBody("value2", ContentType.TEXT_PLAIN))
                .addPart("param3", new StringBody("value3", ContentType.TEXT_PLAIN))
                .addPart("param4", new StringBody("value4", ContentType.TEXT_PLAIN))
                .addPart("file1", excel)
                .addPart("file2", new FileBody(new File("xxxx.jpg")))
                .addPart("file3", new FileBody(new File("xxxx.txt")))
                .build();

        httppost.setEntity(reqEntity);

//            httppost.setHeader("Referer", "http://test.com");
//            httppost.setHeader("Accept-Language", "zh-CN");
//            httppost.setHeader("Content-Type", "multipart/form-data; boundary=---------------------------7e4336143e0100;charset=GBK");
//            httppost.setHeader("Accept-Encoding", "gzip, deflate");
//            httppost.setHeader("Host", "test.com");
//            httppost.setHeader("Connection", "Keep-Alive");
//            httppost.setHeader("Pragma", "no-cache");
        httppost.setHeader("Cookie", "JSESSIONID=xxx; adminid=\"xxx\"");


        System.out.println("执行请求: " + httppost.getRequestLine());
        try (CloseableHttpResponse response = httpclient.execute(httppost)) {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                System.out.println("响应内容长度:" + resEntity.getContentLength());
                System.out.println("响应内容:" + EntityUtils.toString(resEntity, "utf-8"));
            }
            System.out.println("----------------------------------------");
            EntityUtils.consume(resEntity);
        }
    } finally {
        httpclient.close();
    }
关于生成excel流的ContentBody:
    /**
     * 创建excel文件流
     *
     * @param filename 带后缀的文件名
     * @return ContentBody
     */
    private ContentBody newExcelContent(String filename) throws IOException {
        String[] titles = {"title1","title2","title3","title4","title5","title6"};

        String[] data = {"value1","value2","value3","value4","value5","value6"};

        // 创建工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建工作表
        HSSFSheet sheet = workbook.createSheet("sheet1");
        //写入表头内容
        Row titleRow = sheet.createRow(0);
        for (int i = 0; i < titles.length; i++) {
            Cell cell = titleRow.createCell(i);
            cell.setCellValue(titles[i]);
        }
        //写入内容
        Row row = sheet.createRow(1);
        for (int cols = 0; cols < data.length; cols++) {
            Cell cell = row.createCell(cols);
            cell.setCellValue(data[cols]);
        }
        
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        //将excel内容写入流
        workbook.write(bos);
        return new ByteArrayBody(bos.toByteArray(), filename);
    }

OkHttpClient

    OkHttpClient client = new OkHttpClient().newBuilder().build();
    
    MediaType mediaType = MediaType.parse(" multipart/form-data; boundary=---------------------------7e4336143e0100;charset=GBK");

    RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
    .addFormDataPart("param1", "value1")
    .addFormDataPart("param2", "value2")
    .addFormDataPart("param3", "value3")
    .addFormDataPart("param4", "value4")
    .addFormDataPart("file1","test.xls",
        RequestBody.create(MediaType.parse("application/octet-stream"),
        new File("test.xls")))
    .addFormDataPart("file2","xxx.jpg",
        RequestBody.create(MediaType.parse("application/octet-stream"),
        new File("xxx.jpg")))
    .addFormDataPart("file3","xxx.txt",
        RequestBody.create(MediaType.parse("application/octet-stream"),
        new File("xxx.txt")))
    .build();

    Request request = new Request.Builder()
    .url("http://test.com")
    .method("POST", body)
    .addHeader("Referer", "http://test.com")
    .addHeader("Accept-Language", " zh-CN")
    .addHeader("Content-Type", " multipart/form-data; boundary=---------------------------7e4336143e0100;charset=GBK")
    .addHeader("Accept-Encoding", " gzip, deflate")
    .addHeader("Host", "test.com")
    .addHeader("Connection", " Keep-Alive")
    .addHeader("Pragma", " no-cache")
    .addHeader("Cookie", " JSESSIONID=xxx; adminid=\"xxx\"")
    .build();
    Response response = client.newCall(request).execute();
posted @ 2020-09-23 18:25  鹿友  阅读(1559)  评论(0编辑  收藏  举报