HttpClient如何进行文件上传呢?

java-教程王 Java教程 发布时间:2022-04-19 14:59:29 阅读数:6843 1 HttpClient
下文笔者讲述基于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();   
            }   
        }   
    }
参考资料:http://www.java265.com/JavaCourse/202204/2934.html
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaCourse/202204/2938.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者