HttpClient如何进行文件上传呢?

java 文章 2022-07-23 16:00 1975 0 全屏看文

AI助手支持GPT4.0

转自:

http://www.java265.com/JavaCourse/202204/2938.html

HttpClient是一个java语言编写的包,

我们使用HttpClient可以非常方便的发送Http请求

它使基于Http协议请求内容变得非常简单

HttpClient是Apache Jakarta Common下的子项目 它里面封装了很多使用http协议访问的工具,可用于高效访问http


下文笔者讲述基于HttpClient Utils工具类编写一个文件上传的示例分享,如下所示:

HttpClient Utils进行表单进行文件上传的示例分享,如下所示
实现思路:
    1.获取连接
	2.声明一个HttpPost
	3.创建上传体FileBody
	4.定义一个HttpEntity传送文件
	5.execute执行上传操作
	6.获取返回信息
	7.关闭连接
/** 
     * 上传文件 
     */   
    public void upload() {   
        CloseableHttpClient httpclient = HttpClients.createDefault();   
        try {   
            HttpPost httppost = new HttpPost("http://java265.com/uploadFile");   
     
            FileBody bin = new FileBody(new File("F:\image\sendpix0.jpg"));   
            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();   
            }   
        } catch (ClientProtocolException e) {   
            e.printStackTrace();   
        } catch (IOException e) {   
            e.printStackTrace();   
        } finally {   
            try {   
   httpclient.close();   
            } catch (IOException e) {   
   e.printStackTrace();   
            }   
        }   
    }
-EOF-

AI助手支持GPT4.0


国内超级便宜服务器

摸鱼人热门新闻聚合

钻级赞助商 我要加入

开发者在线工具

第三方支付技术请加QQ群

相关文章
Java生成32,16位的md5
mybatis 拦截器
FileOutputStream(文件字节输出流)
springJdbcTemplate 执行 sql中包含in的用法
Java获取微信access_token(支持缓存)
随便看看
微信公众号免300认证教程 5892
小程序已经上线,作为管理员无法在小程序数据助手查看数据? 5299
小程序广告组件通过审核,但是小程序内没有显示广告? 5067
企业微信通讯录账号被管理员误/恶意删除,怎么办? 9568
问题? 9047
如何快速搭建抽奖助手小程序(无需代码知识) 6176
许涛 大哥在吗, 要解冻小程序的时候提示信息主体不一致, 能帮忙看下吗? 7471
小程序搜一搜全称搜索不显示 麻烦解决一下!谢谢 6792
我的小程序广告收款主体是个体工商户,每个月邮寄两次发票很是麻烦,我年底的时候打包邮寄一次可以么? 6126
如何解决渲染层网络错误Failed to load media? 17393