java- 后端调用第三方上传文件接口----笔记

 

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class Test2 {
    public static void main(String[] args) {
        try {
            Map<String,String> map = new HashMap<String,String>();
            map.put("user", "xxx");map.put("pwd", "xxx");
            Map<String, InputStream> inputStreamMap = new HashMap<>();
            inputStreamMap.put("测试文件1.xlsx",new FileInputStream("E:\\测试文件1.xlsx"));
            inputStreamMap.put("测试文件2.xlsx",new FileInputStream("E:\\测试文件2.xlsx"));
            String token = "token";
            Map<String,String> headlerInfo= new HashMap<>();
            headlerInfo.put("token", token);
            String result = doPostInputStream("http://localhost/InputStreamTest", inputStreamMap, map,headlerInfo);
            System.out.println(result );
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
    public static final String CHARSET = "UTF-8";
    private static ThreadLocal<Map<String, String>> httpHeader = new ThreadLocal<Map<String, String>>();
    private static ThreadLocal<Map<String, Object>> httpClientConfig = new ThreadLocal<Map<String, Object>>();
    // 连接超时时间
    public static final String CONNECT_TIMEOUT = "connect_timeout";
    // socket超时时间
    public static final String SOCKET_TIMEOUT = "socket_timeout";
    public static final Integer DEFAULT_CONNECT_TIMEOUT = 6000;
    public static final Integer DEFAULT_SOCKET_TIMEOUT = 6000;
    /**
     * 
     * @param host 请求地址
     * @param inputStreamMap 上传文件
     * @param param 参数
     * @param header 请求头
     * @return
     * @throws IOException
     */
    public static String doPostInputStream(String host, Map<String, InputStream> inputStreamMap, Map<String,String> param,Map<String,String> header) throws IOException {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpPost httpPost = null;
        try {
            //设置请求属性
            httpClient = addHttpClient();
            //添加请求头
            httpPost = new HttpPost(host);
            addHeader(httpPost, header);
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE).setCharset(StandardCharsets.UTF_8);
            int count = 0;
            for (Map.Entry<String,InputStream> entry : inputStreamMap.entrySet()){
                multipartEntityBuilder.addBinaryBody("files"+count, entry.getValue(), ContentType.DEFAULT_BINARY,entry.getKey());
                count++;
            }
            param.forEach((key,value)->{
                StringBody paramJson = new StringBody(value, ContentType.create( "text/plain", Consts.UTF_8));
                multipartEntityBuilder.addPart(key,paramJson);
            });
            HttpEntity reqEntity = multipartEntityBuilder.build();
            httpPost.setEntity(reqEntity);
            response = httpClient.execute(httpPost);
            String result = null;
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                result = EntityUtils.toString(resEntity, Charset.forName("UTF-8"));
            }
            //销毁
            EntityUtils.consume(resEntity);
            return result;
        }catch (Exception e){
            //返回异常
            return e.getMessage();
        }finally {
            if (response != null) {
                response.close();
            }
            if (httpPost != null) {
                httpPost.releaseConnection();
            }
            if (httpClient != null) {
                httpClient.close();
            }
        }
    }
    /**
     * 
     * @return
     */
    public static CloseableHttpClient addHttpClient() {
        Map<String, Object> configSetting = new HashMap<String, Object>();
        if (httpClientConfig != null && null != httpClientConfig.get()) {
            configSetting = httpClientConfig.get();
        }
        RequestConfig.Builder builder = RequestConfig.custom();
        Integer connectTimeout = DEFAULT_CONNECT_TIMEOUT;
        if (configSetting.get(CONNECT_TIMEOUT) != null) {
            try {
                connectTimeout = Integer.valueOf(configSetting.get(CONNECT_TIMEOUT).toString());
            } catch (Exception e) {
                connectTimeout = DEFAULT_CONNECT_TIMEOUT;
            }
        }
        //连接超时时间
        builder.setConnectTimeout(connectTimeout);
        //socket超时时间
        Integer socketTimeout = DEFAULT_SOCKET_TIMEOUT;
        if (configSetting.get(SOCKET_TIMEOUT) != null) {
            try {
                socketTimeout = Integer.valueOf(configSetting.get(SOCKET_TIMEOUT).toString());
            } catch (Exception e) {
                socketTimeout = DEFAULT_SOCKET_TIMEOUT;
            }
        }
        builder.setSocketTimeout(socketTimeout);
        RequestConfig config = builder.build();
        return HttpClientBuilder.create().setDefaultRequestConfig(config).build();
    }
    /**
     * 添加请求头
     * @param requestBase
     */
    private static void addHeader(HttpRequestBase requestBase,Map<String,String> map) {
        try {
            //固定请求头
            if (httpHeader != null && httpHeader.get() != null) {
                Map<String, String> ma = httpHeader.get();
                for (String key : ma.keySet()) {
                    requestBase.addHeader(key, ma.get(key));
                }
            }
            //特殊请求头
            for (String key : map.keySet()) {
                requestBase.addHeader(key, map.get(key));
            }
        } catch (Exception e) {
        }
    }

}
 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值