HttpClients多文件上传连接 WebODM 中创建任务接口的方法

来源:互联网 发布:js失去焦点事件 编辑:程序博客网 时间:2024/05/29 02:45
/** * 创建一个任务 * @param url  WebODM 中的一个接口 url * @param path 文件所在本地文件夹的路径 * @param options   配置参数 * @return */public static String sendPostCreatePro3 (String url, String path, String options) {String result = "";String token = Token.token;// 获取 TokenCloseableHttpClient httpClient = HttpClients.createDefault(); //一、 创建 HttpClients 的实例 CloseableHttpResponse response = null;try {MultipartEntityBuilder builder = MultipartEntityBuilder.create(); //1、 创建多实体生成器builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); //a、 设置浏览器兼容模式builder.setCharset(CharsetUtils.get("UTF-8"));//b、 设置字符集编码//2、 将 多文件 addPart 到多实体生成器中File file = new File(path); //a、 根据多文件所在本地文件夹的路径创建 File 对象if (!file.exists()) {return path + "not exists";}File[] files = file.listFiles();  //b、 获取并遍历该 本地文件夹 中所有的文件和文件夹的 List 集合for (int i = 0; i < files.length; i++) {File fi = files[i];if (fi.isDirectory()) { // 测试此抽象路径名表示的文件是否是一个目录。log.info(fi.getName() + "[目录]"); } else {log.info(fi.getName());String filePath = path.concat(fi.getName()); //c、 如果是文件,将其拼接成完整的本地路径并 addPart 到多实体生成器中builder.addPart("img" + i, new FileBody(new File(filePath)));}}builder.addPart("options", new StringBody(options, ContentType.create("application/json", Consts.UTF_8))); //3、 将配置参数 addPart 的多实体生成器中HttpEntity entity = builder.build(); //4、 获得多实体生成器的实体HttpPost httpPost = new HttpPost(url); //二、 通过传入的 url 创建连接方法的 实例httpPost.setEntity(entity);   //1、将多实体生成器的实体 set 到 连接方法的实例中httpPost.setHeader("Authorization", "JWT " + token); //2、 通过 Token, 设置表头 (WebODM 接口要求)response = httpClient.execute(httpPost);  //三、 执行该连接方法并返回响应HttpEntity repEntity = response.getEntity(); //1 、 获得响应的实体result = EntityUtils.toString(repEntity, Charset.forName("UTF-8")); //2、 获取响应实体内容 EntityUtils.consume(repEntity); //3、 确保实体内容已完全消耗,并且关闭内容流(如果存在)。} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {if (response != null) {response.close(); //4、 关闭响应}httpClient.close();  //四、  关闭 httpClient} catch (IOException e) {e.printStackTrace();}}return result;}
原创粉丝点击