Java代码中发起post请求携带文件

   /**
     *
     *form表单提交(带附件)
     *
     *
     */
    public  String doPost(String url, List list) throws Exception {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
        String resultString ="";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);


            //传参


            //流文件入参
            if (!StringUtils.isEmpty(list) && !list.isEmpty()) {
                for (MultipartFile s : list) {
                    if(!StringUtils.isEmpty(s)){
                        multipartEntityBuilder.addBinaryBody("files", s.getInputStream(), ContentType.create("multipart/form-data", Consts.UTF_8), s.getOriginalFilename());
                    }
                }
            }

            HttpEntity httpEntity = multipartEntityBuilder.build();
            httpPost.setEntity(httpEntity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");

        } finally {
            if (response != null) {
                response.close();
            }
        }
        return resultString ;
    }

你可能感兴趣的:(java,开发语言,后端)