HttpClient文件上传

来源:互联网 发布:重大误解知乎 编辑:程序博客网 时间:2024/06/06 00:35

HttpComponents是一个HTTP工具集,其中HttpClient包括了HTTP客户端的API,可以充当浏览器。

用HttpClient API 实现文件上传的代码网上有很多,但是都更新不及时,版本较低。

以下代码的HttpClient版本是4.3.1:

    CloseableHttpClient httpclient = HttpClientBuilder.create().build();    CloseableHttpResponse response = null;    try {        HttpPost httppost = new HttpPost(UPLOAD_URL);        HttpEntity req = MultipartEntityBuilder.create()        .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)        .addPart("files", new FileBody(new File(FILE1_PATH)))        .addPart("files", new FileBody(new File(FILE2_PATH)))        .build();        httppost.setEntity(req);        System.out.println("executing request: " + httppost.getRequestLine());        response = httpclient.execute(httppost);                HttpEntity re = response.getEntity();        System.out.println(response.getStatusLine());        if (re != null) {            System.out.println("Response content: " +             new BufferedReader(new InputStreamReader(re.getContent())).readLine());        }        EntityUtils.consume(re);    } finally {        try {        response.close();        } catch (Exception e) {        e.printStackTrace();        }    }


代码的依赖包:

<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.3.1</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpmime</artifactId><version>4.3.1</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency>


原创粉丝点击