java技术分享

HttpClien用multipart/form-data上传文件方法

1.接口调用封装:
定义map

List item


```java
 Map<String, ContentBody> reqParam = new HashMap<String, ContentBody>();

  /*
                         * 封装参数
                         * */
                        ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
                        reqParam.put("analyzeType", new StringBody(projectAiModel.getSn(), ContentType.MULTIPART_FORM_DATA));
                        reqParam.put("deviceID", new StringBody(deviceId, ContentType.MULTIPART_FORM_DATA));
                        reqParam.put("extend", new StringBody("", ContentType.MULTIPART_FORM_DATA));
                        reqParam.put("file", new FileBody(new File(multipartFile.getName())));
                        reqParam.put("fileUri", new StringBody(url, ContentType.MULTIPART_FORM_DATA));
                        reqParam.put("filterDuplicates", new StringBody(String.valueOf(true), ContentType.MULTIPART_FORM_DATA));
                        reqParam.put("objectType", new StringBody(AnalyzeMaterialEnum.IMAGE.toString(), ContentType.MULTIPART_FORM_DATA));
                        reqParam.put("requestID", new StringBody(requestId, ContentType.MULTIPART_FORM_DATA));
                        /*
                         * 上传图片,调用以下工具类`在这里插入代码片`
                         * */
                        String post = HttpRequestUtil.doPost(aiSubscriber.getUrl(), athorization, reqParam);
                 
**2.HttpRequestUtil (接口调用工具类)**
/**
 * Created by wdy on 2021/7/07
 * 接口调用工具类
 */
public class HttpRequestUtil {
    private static CloseableHttpClient httpClient;

    static {
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(100);
        cm.setDefaultMaxPerRoute(20);
        cm.setDefaultMaxPerRoute(50);
        httpClient = HttpClients.custom().setConnectionManager(cm).build();
    }

    public static String doGet(String url) {
        CloseableHttpResponse response = null;
        BufferedReader in = null;
        String result = "";
        try {
            HttpGet httpGet = new HttpGet(url);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
            httpGet.setConfig(requestConfig);
            httpGet.setConfig(requestConfig);
            httpGet.addHeader("Content-type", "application/json; charset=utf-8");
            httpGet.setHeader("Accept", "application/json");
            response = httpClient.execute(httpGet);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();
            result = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }




    public static String doPost(String url, String athorization, Map<String, ContentBody> reqParam) throws ClientProtocolException, IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();

        try {
            // 创建httpget.
            HttpPost httppost = new HttpPost(url);

            //setConnectTimeout:设置连接超时时间,单位毫秒。setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。setSocketTimeout:请求获取数据的超时时间,单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
            RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(15000).build();
            httppost.setConfig(defaultRequestConfig);
            httppost.addHeader("Authorization", athorization);
            System.out.println("executing request " + httppost.getURI());
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            for (Map.Entry<String, ContentBody> param : reqParam.entrySet()) {
                multipartEntityBuilder.addPart(param.getKey(), param.getValue());
            }
            HttpEntity reqEntity = multipartEntityBuilder.build();
            httppost.setEntity(reqEntity);
            // 执行post请求.
            CloseableHttpResponse response = httpclient.execute(httppost);
            System.out.println("got response");

            try {
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                //System.out.println("--------------------------------------");
                // 打印响应状态
                //System.out.println(response.getStatusLine());
                if (entity != null) {
                    return EntityUtils.toString(entity, Charset.forName("UTF-8"));
                }
                //System.out.println("------------------------------------");
            } finally {
                response.close();

            }
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值