java post请求form表单格式发送数据,ContentType=multipart/form-data

/**
    * post请求form表单格式发送数据
    *  multipart/form-data
    * @param url 接口地址
    * @param param 参数数组
    * @return 返回结果
    * @throws IOException
    */
   public static String sendPost(String url, Map<String, String> param) throws IOException {
       CloseableHttpClient httpclient = HttpClients.createDefault();
       String result = "";
       try {
           HttpPost httppost = new HttpPost(url);
           //构建超时等配置信息
           RequestConfig config = RequestConfig.custom().setConnectTimeout(1000) //连接超时时间
                   .setConnectionRequestTimeout(1000) //从连接池中取的连接的最长时间
                   .setSocketTimeout(10 * 1000) //数据传输的超时时间
                   .build();
           httppost.setConfig(config);
           MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
           ContentType strContent = ContentType.create("text/plain", Charset.forName("UTF-8"));
           //参数填充
           for (String key : param.keySet()) {
               entityBuilder.addTextBody(key, param.get(key),strContent);
           }
           HttpEntity entity = entityBuilder.build();
           httppost.setEntity(entity);
           CloseableHttpResponse response = httpclient.execute(httppost);
           try {
               HttpEntity resEntity = response.getEntity();
               //回复接收
               result = EntityUtils.toString(resEntity, "UTF-8");
           } finally {
               response.close();
           }
       } catch (Exception e) {
           logger.error(e.getMessage());
           throw e;
       } finally {
           httpclient.close();
       }
       return result;
   }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值