httpclient4.3上传文件

最近做第三方api对接, 用到http文件上传和普通的post请求所以记录下.
分别引用了这两位老哥的文档
Apache HttpClient 4.5 Multipart Upload Request Example
HttpClient超时设置详解

在引入jar包上, 第一个链接引用的是

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.3</version>
    </dependency>
    <!-- Apache HttpClient Mime -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpmime</artifactId>
        <version>4.5.3</version>
    </dependency>

不知道为何其实httpmime里边有包含httpclient的jar包的,但是外这篇外文也有引用.但是无所谓拉.
其实我用的是4.3.5 哈哈
下面直接上代码post请求上传文件

/**
     * http post方式上传文件
     * httpPost
     * @param url
     * @param headers 请求头信息
     * @param bodyMap 请求体信息 只支持文件,可以多文件,不过后端接受文件比较麻烦 因为每个都文件都有一个name,
     *                而spring获取文件都是通过@RequestParam("uploadFile") MultipartFile file的方式来获取
     * @return org.apache.http.HttpEntity
     */
    public static String httpPost(String url, Map<String, String> headers, Map<String, File> bodyMap) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // result
        String result = "";
        try {
            HttpPost httpPost = new HttpPost(url);
            // 设置请求和传输超时时间
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(10_000)
                    .setConnectionRequestTimeout(10_000)
                    .setSocketTimeout(10_000).build();
            httpPost.setConfig(requestConfig);
            headers.forEach((key, value) -> httpPost.setHeader(key, value));
            //构造请求体
            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
            // 以浏览器兼容模式运行,防止文件名乱码。
            entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            // 设置二进制的方式上传文件addBinaryBody() 如果是表单 用addPart() 主要用哪一个看需求
            if (bodyMap != null) {
                bodyMap.forEach((key, value) -> entityBuilder.addBinaryBody(key, value));
            }
            HttpEntity reqEntity = entityBuilder.setCharset(CharsetUtils.get("UTF-8")).build();
            httpPost.setEntity(reqEntity);

            // System.out.println("发起请求的页面地址 " + httpPost.getRequestLine());
            // 发起请求 并返回请求的响应
            CloseableHttpResponse response = httpClient.execute(httpPost);
            try {
                // 获取响应对象
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, Charset.forName("UTF-8"));
                }
                /***
                 // 想看可以打开注释
                 // 打印响应状态
                 // System.out.println("response StatusLin:" + response.getStatusLine());
                 // 打印http状态码
                 // System.out.println("response code:" + response.getStatusLine().getStatusCode());
                 if (resEntity != null) {
                 // 响应长度
                 System.out.println("Response content length: "
                 + resEntity.getContentLength());
                 // 响应内容
                 System.out.println("response content: " + result);
                 }
                 */
                // 销毁
                EntityUtils.consume(resEntity);
            } finally {
                if (response != null) {
                    response.close();
                }
            }
        } finally {
            if (httpClient != null) {
                httpClient.close();
            }
        }
        return result;
    }

有时候会遇到timeout的问题 需要设置时间再长一些,因为小编遇到的就比较忙,大概15s才响应,开始还以为是自己代码问题.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值