博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Httpclient 4.x文件上传
阅读量:6963 次
发布时间:2019-06-27

本文共 2249 字,大约阅读时间需要 7 分钟。

hot3.png

依赖jar包:httpclient-4.4.jar、httpcore-4.4.jar、httpmime-4.4.x.jar

/** * httpclient4.x 文件上传 *  * Example how to use multipart/form encoded POST request. */public class ClientMultipartFormPost {     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();        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());            CloseableHttpResponse response = httpclient.execute(httppost);                      System.out.println(response.getStatusLine());            HttpEntity 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();                }            }        }    } }

 

转载于:https://my.oschina.net/crazybird/blog/758557

你可能感兴趣的文章
Centos下源码安装MySQL5.5(单实例)
查看>>
我的友情链接
查看>>
访问服务器(加载图片)
查看>>
一个搞ACM需要掌握的算法
查看>>
kvm-net模式(三)
查看>>
rpmのyum详解
查看>>
Ansible配置及使用
查看>>
java inputStream ,outputStream
查看>>
系统服务
查看>>
Linux 文件与目录管理+用户管理命令
查看>>
C#中父类和子类之间相互转换
查看>>
《Linux菜鸟入门2》mail服务
查看>>
Mysql DOS: 进入Mysql运行文目录 F:\mysql-8.0.13-winx64\bin
查看>>
中小型企业网络构建之路由的简单配置
查看>>
Create an inbound email action
查看>>
oracle教程之DML事务锁定的机制
查看>>
Oracle RMAN 维护(一)--RMAN的维护
查看>>
centos6.6关闭防火墙和selinux
查看>>
JAVA RMI远程方法调用简单实例
查看>>
Citrix桌面虚拟化解决方案介绍
查看>>