通过HttpClient4.5模拟Form表单文件上传

Posted YSHY

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了通过HttpClient4.5模拟Form表单文件上传相关的知识,希望对你有一定的参考价值。

public static void main(String[] args) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = null;

        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream("D:\\test.pdf");

            HttpPost httpPost = new HttpPost("http://127.0.0.1/test");

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            builder.addBinaryBody("wj", inputStream, ContentType.create("multipart/form-data"), "test.pdf");
            
            //构建请求参数 普通表单项  
            StringBody stringBody = new StringBody("100001", ContentType.MULTIPART_FORM_DATA);
            builder.addPart("serial_no", stringBody);
            stringBody = new StringBody("200", ContentType.MULTIPART_FORM_DATA);
            builder.addPart("xPosition", stringBody);
            stringBody = new StringBody("200", ContentType.MULTIPART_FORM_DATA);
            builder.addPart("yPosition", stringBody);
            stringBody = new StringBody("2", ContentType.MULTIPART_FORM_DATA);
            builder.addPart("sealType", stringBody);
            stringBody = new StringBody("1", ContentType.MULTIPART_FORM_DATA);
            builder.addPart("paegNum", stringBody);
            
            builder.setCharset(CharsetUtils.get("UTF-8"));

            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);

            response = httpclient.execute(httpPost);

            int statusCode = response.getStatusLine().getStatusCode();

            System.out.println("statusCode:" + statusCode);

            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity resEntity = response.getEntity();
                result = EntityUtils.toString(resEntity, "UTF-8");
            }

            System.out.println("result:" + result);
        } catch (IOException ex) {
            Logger.getLogger(QzTest.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (null != inputStream) {
                    inputStream.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(QzTest.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                httpclient.getConnectionManager().shutdown();
            }
        }
    }

依赖包:

commons-logging-1.2.jar

httpclient-4.5.3.jar

httpcore-4.4.6.jar

httpmime-4.5.3.jar

以上是关于通过HttpClient4.5模拟Form表单文件上传的主要内容,如果未能解决你的问题,请参考以下文章

在 c# HttpClient 4.5 中发布 multipart/form-data

js 上传文件模拟Form 表单

apipost怎么模拟表单提交下载功能

c# 模拟表单提交,post form 上传文件大数据内容

PHP CURL 模拟form表单上传遇到的小坑

c#代码,模拟form表单发送post请求,上传文件(并带其他参数)