http使用formData方式传输文件请求

转载请注明出处:

  项目中有遇到http使用formData请求传输文件,在此记录一下

1.依赖jar包:

    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.2</version>
    </dependency>

2.代码:

复制代码
// 定义httpClient和response
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();;
        CloseableHttpResponse response = null;
        try {
            // 定义Post请求
            HttpPost httpPost = new HttpPost(uri);
            // 设置配置
            Builder builder = createBuilder();
            RequestConfig config = null;
            // 是否开启代理模式访问
            if (enabled) {
                HttpHost proxy = new HttpHost(host, port, Proxy.Type.HTTP.toString());
                config = builder.setProxy(proxy).build();
            } else {
                config = builder.build();
            }
            httpPost.setConfig(config);
            // 设置请求头
           // httpPost.setHeader(FucdnStrConstant.ACCEPT.getConstant(), MediaType.MULTIPART_FORM_DATA_VALUE);
            httpPost.setHeader(FucdnStrConstant.CONTENT_TYPE.getConstant(), MediaType.MULTIPART_FORM_DATA_VALUE);
            // 发送请求得到返回数据
            httpPost.setEntity(fileBuilder.build());
            // 得到响应
            response = httpClient.execute(httpPost);
            // 状态码
           int statusCode = response.getStatusLine().getStatusCode();
            // 响应内容
            HttpEntity entity = response.getEntity();
            // 响应内容
            String responseContent = EntityUtils.toString(entity);
        } catch (Exception e) {
            throw new FucdnException(e);
        } finally {
            // 关闭流
            Utils.closeStream(response);
            Utils.closeStream(httpClient);
        }
复制代码

  

   

复制代码
 private Builder createBuilder() {
            // init Builder and init TIME_OUT
            return RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000)
                    .setConnectionRequestTimeout(20000);
        }
    
    
 public static void closeStream(Closeable c) {
            // 流不为空
            if (c != null) {
                try {
                    // 流关闭
                    c.close();
                } catch (IOException ex) {
                    LOGGER.error("closeStream failed", ex);
                }
            }
    }
复制代码

 


posted @   香吧香  阅读(12250)  评论(0编辑  收藏  举报
编辑推荐:
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2018-05-14 高并发解决方案
2017-05-14 maven插件安装
点击右上角即可分享
微信分享提示