HttpClient:模拟表单提交文件,发送multipart/form-data数据

使用HttpClient来模拟表单提交,传送文件
常用于非web客户端与web后端传输文件

1.pom

<dependencies>

<dependency>
    <groupId>org.apache.httpcomponentsgroupId>
    <artifactId>httpclientartifactId>
    <version>4.5.2version>
dependency>


<dependency>
    <groupId>org.apache.httpcomponentsgroupId>
    <artifactId>httpmimeartifactId>
    <version>4.5.2version>
dependency>

2.post data

public class PostMultiData {
    public static void main(String[] args) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            String uri = "http://127.0.0.1:8080/encoding/servlet/RevFileServlet";
            uri="http://127.0.0.1:8080/revFile";
            HttpPost httppost = new HttpPost(uri);

            String path="C:/Users/Administrator/Desktop/study/微服务/netflix/eureka.png";
            File file = new File(path);
            FileBody bin = new FileBody(file);
            StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

            HttpEntity reqEntity = MultipartEntityBuilder.create()
                    .addPart("bin", bin)
                    .addPart("comment", comment)
                    .build();


            httppost.setEntity(reqEntity);

            System.out.println("executing request " + httppost.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    System.out.println("Response content length: " + resEntity.getContentLength());
                }
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }
}

你可能感兴趣的:(httpclient)