美文网首页技术干货
Httpclient 4.x文件上传

Httpclient 4.x文件上传

作者: Java及SpringBoot | 来源:发表于2018-05-21 17:47 被阅读4次
public static void main(String[] args) {
    String url = "http://localhost:8080/fileRequest";
    File file = new File("/home/opt/fileUpload/A.zip");
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpEntity resEntity = null;
    CloseableHttpResponse response = null;
    try {
        HttpPost httppost = new HttpPost(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        //others param for request
        StringBody stringFileNameBody = new StringBody("fileName", ContentType.create("text/plain", "UTF-8"));
        builder.addPart("name", stringFileNameBody);
        StringBody stringFileMd5 = new StringBody("md5", ContentType.create("text/plain", "UTF-8"));
        builder.addPart("name", stringFileMd5);

        //file param for request
        String fileRequestParam = "file";
        FileBody fileBody = new FileBody(file, ContentType.create("multipart/form-data", "UTF-8"));
        builder.addPart(fileRequestParam, fileBody);

        HttpEntity reqEntity = builder.build();
        httppost.setEntity(reqEntity);
        System.out.println("executing request " + httppost.getRequestLine());
        response = httpclient.execute(httppost);

        System.out.println(response.getStatusLine());
        resEntity = response.getEntity();
        if (resEntity != null) {
            System.out.println("Response content length: " + resEntity.getContentLength());
        }
        EntityUtils.consume(resEntity);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            EntityUtils.consume(resEntity);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

相关文章

网友评论

    本文标题:Httpclient 4.x文件上传

    本文链接:https://www.haomeiwen.com/subject/jhjqjftx.html