百炼平台Java 集成API上传文档到数据中心并添加索引

本文涉及的产品
NLP 自学习平台,3个模型定制额度 1个月
视觉智能开放平台,图像资源包5000点
视觉智能开放平台,分割抠图1万点
简介: 本文主要演示阿里云百炼产品,如何通过API实现数据中心文档的上传和索引的添加。

一、主要操作步骤

图片.png

二、参数获取

  • categoryId:数据中心类目id

图片.png

  • workspaceId:业务空间id

图片.png

  • indexId:索引id

图片.png

  • ak、sk

ACCESS_KEY_ID、ACCESS_KEY_SECRET参数获取地址

hiwspwhvrvbmc_2efd51003f384b0c8d043538cf44f1a7.png

三、完整的JAVA Code Sample

  • pom.xml
 <dependencies>

        <!-- https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>dashscope-sdk-java</artifactId>
            <version>2.15.1</version>
        </dependency>

        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>bailian20231229</artifactId>
            <version>1.4.1</version>
        </dependency>
    </dependencies>
  • Code

import com.google.gson.internal.LinkedTreeMap;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;

public class apply {

    public static void main(String[] args_) throws Exception {

        // 上传文件的本地路径地址
        String filePath = "C:\\Users\\*****\\1.0.01.04.36569.docx";
        String categoryId = "cate_d78d9993**********";//数据中心类目id
        String workspaceId = "llm-w*******"; //业务空间id
        String indexId = "eev*******";// 索引库索引id
        String ak = "LT*********";
        String sk = "8R**********";

        // 初始化参数
        String md5 = "";
        String byteLength = "";
        String fileName = "";

        try {
            Path path = Paths.get(filePath);
            fileName = path.getFileName().toString();
            // 读取文件内容到字节数组
            byte[] fileBytes = Files.readAllBytes(path);

            // 获取文件字节内容长度
            byteLength = fileBytes.length + "";
            // 计算MD5值
            md5 = calculateMD5(fileBytes);

        } catch (IOException | NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        // 初始化Client对象
        com.aliyun.teaopenapi.Client client = apply.createClient(ak, sk);

        //1、申请文件上传租约
        HashMap<String,Object> response = apply.applyFileUploadLease(client, fileName,md5,byteLength,categoryId,workspaceId);

        // 从response中提取data,获取上传文件必要的url和
        if(response.containsKey("body")){
            LinkedTreeMap<String, Object> body1 = (LinkedTreeMap<String, Object>) response.get("body");
            if (body1.containsKey("Data")) {
                LinkedTreeMap<String, Object> dataObject = (LinkedTreeMap<String, Object>) body1.get("Data");
                // 这里是你需要的Data对象
                String fileUploadLeaseId = (String) dataObject.get("FileUploadLeaseId");
                String type = (String) dataObject.get("Type");
                LinkedTreeMap<String, Object> param = (LinkedTreeMap<String, Object>) dataObject.get("Param");
                String preSignedUrl = (String) param.get("Url");

                LinkedTreeMap<String, Object> headers = (LinkedTreeMap<String, Object>) param.get("Headers");
                String contentType = (String) headers.get("Content-Type");
                String extra = (String) headers.get("X-bailian-extra");

                //2、使用租约上传文档
                uploadFile(preSignedUrl,filePath,extra,contentType,Integer.parseInt(byteLength));

                //3、addfile,添加上传的文档到百炼系统,系统自动解析文档
                String fileId = addFile(client, fileUploadLeaseId, workspaceId, categoryId);

                //4、将解析的文档添加到索引
                AddDocumentsJob(client,indexId,workspaceId,fileId,categoryId);

            }else {
                System.out.println("body not found in response.");
            }
        }
    }



    /**
     * <b>description</b> :
     * <p>使用AK & SK初始化账号Client</p>
     * @return Client
     *
     * @throws Exception
     */
    public static com.aliyun.teaopenapi.Client createClient(String ak, String sk) throws Exception {
        // 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378657.html。
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(ak)
                // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(sk);
        // Endpoint 请参考 https://api.aliyun.com/product/bailian
        config.endpoint = "bailian.cn-beijing.aliyuncs.com";
        return new com.aliyun.teaopenapi.Client(config);
    }

    /**
     * <b>申请文档上传租约</b> :
     * <p>API 相关</p>
     * @return OpenApi.Params
     */
    public static com.aliyun.teaopenapi.models.Params createApplyFileUploadLeaseApiInfo(String CategoryId, String WorkspaceId) throws Exception {
        com.aliyun.teaopenapi.models.Params params = new com.aliyun.teaopenapi.models.Params()
                // 接口名称
                .setAction("ApplyFileUploadLease")
                // 接口版本
                .setVersion("2023-12-29")
                // 接口协议
                .setProtocol("HTTPS")
                // 接口 HTTP 方法
                .setMethod("POST")
                .setAuthType("AK")
                .setStyle("ROA")
                // 接口 PATH
                .setPathname("/" + WorkspaceId + "/datacenter/category/" + CategoryId + "")
                // 接口请求体内容格式
                .setReqBodyType("formData")
                // 接口响应体内容格式
                .setBodyType("json");
        return params;
    }

    public static HashMap<String,Object> applyFileUploadLease(com.aliyun.teaopenapi.Client client, String fileName, String md5, String byteLength, String categoryId, String workspaceId ) throws Exception{
        com.aliyun.teaopenapi.models.Params params = apply.createApplyFileUploadLeaseApiInfo(categoryId, workspaceId);
        // body params
        java.util.Map<String, Object> body = new java.util.HashMap<>();
        body.put("FileName", fileName);
        body.put("Md5", md5);
        body.put("SizeInBytes", byteLength);
        // runtime options
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        com.aliyun.teaopenapi.models.OpenApiRequest request = new com.aliyun.teaopenapi.models.OpenApiRequest()
                .setBody(body);
        // 返回值为 Map 类型,可从 Map 中获得三类数据:响应体 body、响应头 headers、HTTP 返回的状态码 statusCode。
        HashMap<String,Object> response = (HashMap<String, java.lang.Object>)  client.callApi(params, request, runtime);
        return response;
    }

    /**
     * 计算md5值
     * @param bytes
     * @return
     * @throws NoSuchAlgorithmException
     */
    private static String calculateMD5(byte[] bytes) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] digest = md.digest(bytes);
        return byteArrayToHexString(digest);
    }

    private static String byteArrayToHexString(byte[] bytes) {
        Formatter formatter = new Formatter();
        for (byte b : bytes) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    /**
     * 使用获取到的租约上传实际文件到数据中心,注意这一步上传后在数据中心还看不到文档,AddFile之后才可以在数据中心看到添加的文档
     * @param preSignedUrl
     * @param filePath
     * @param extra
     * @param contentType
     * @param length
     */
    public static void uploadFile(String preSignedUrl, String filePath,String extra,String contentType,int length ) {
        HttpURLConnection connection = null;
        try {
            // 创建URL对象

            URL url = new URL(preSignedUrl);
            connection = (HttpURLConnection) url.openConnection();
            // 设置请求⽅法为PUT,预签名URL默认⽤于PUT操作进⾏⽂件上传

            connection.setRequestMethod("PUT");
            // 允许向connection输出,因为这个连接是⽤于上传⽂件的

            connection.setDoOutput(true);
            // 设置请求头,这⾥可以根据需要设置⽐如Content-Type

            connection.setRequestProperty("X-bailian-extra", extra);
            connection.setRequestProperty("Content-Type", contentType);
            // 读取⽂件并通过连接上传

            try (DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());
                 FileInputStream fileInputStream = new FileInputStream(filePath)) {
                byte[] buffer = new byte[length];
                int bytesRead;
                while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, bytesRead);
                }
                outStream.flush();
            }
            // 检查响应代码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // ⽂件上传成功处理

                System.out.println("File uploaded successfully.");
            } else {
                // ⽂件上传失败处理

                System.out.println("Failed to upload the file. ResponseCod e: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    /**
     * 构建添加文档API
     * @param WorkspaceId
     * @return
     * @throws Exception
     */
    public static com.aliyun.teaopenapi.models.Params createAddFileApiInfo(String WorkspaceId) throws Exception {
        com.aliyun.teaopenapi.models.Params params = new com.aliyun.teaopenapi.models.Params()
                // 接⼝名称
                .setAction("AddFile")
                // 接⼝版本
                .setVersion("2023-12-29")
                // 接⼝协议
                .setProtocol("HTTPS")
                // 接⼝ HTTP ⽅法
                .setMethod("PUT")
                .setAuthType("AK")
                .setStyle("ROA")
                // 接⼝ PATH
                .setPathname("/" + WorkspaceId + "/datacenter/file")
                // 接⼝请求体内容格式
                .setReqBodyType("formData")
                // 接⼝响应体内容格式
                .setBodyType("json");
        return params;
    }

    /**
     * AddFile
     * 该接口用于将已经成功上传的文档添加到百炼系统数据中心,添加成功之后,系统会自动启动文件的解析,在数据中心可以看到文档
     * @param client
     * @param leaseId
     * @param workSpaceId
     * @param categoryId
     * @throws Exception
     */
    public static String addFile(com.aliyun.teaopenapi.Client client,String leaseId,String workSpaceId,String categoryId) throws Exception {
        com.aliyun.teaopenapi.models.Params params = apply.createAddFileApiInfo(workSpaceId);
        // body params
        java.util.Map<String, Object> body = new java.util.HashMap<>();
        body.put("LeaseId", leaseId);
        body.put("Parser", "DASHSCOPE_DOCMIND");
        body.put("CategoryId", categoryId);
        // runtime options
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        com.aliyun.teaopenapi.models.OpenApiRequest request = new com.aliyun.teaopenapi.models.OpenApiRequest()
                .setBody(body);
        // 复制代码运行请自行打印 API 的返回值
        // 返回值为 Map 类型,可从 Map 中获得三类数据:响应体 body、响应头 headers、HTTP 返回的状态码 statusCode。
        HashMap<String,Object> response = (HashMap<String, Object>) client.callApi(params, request, runtime);

        LinkedTreeMap<String, Object> file_body = (LinkedTreeMap<String, Object>) response.get("body");
        LinkedTreeMap<String, Object> data = (LinkedTreeMap<String, Object>) file_body.get("Data");
        String fileId = (String) data.get("FileId");
        System.out.println("addFile:" + response.get("statusCode"));
        return fileId;
    }

    public static com.aliyun.teaopenapi.models.Params createSubmitIndexAddDocumentsJobApiInfo(String WorkspaceId) throws Exception {
        com.aliyun.teaopenapi.models.Params params = new com.aliyun.teaopenapi.models.Params()
                // 接口名称
                .setAction("SubmitIndexAddDocumentsJob")
                // 接口版本
                .setVersion("2023-12-29")
                // 接口协议
                .setProtocol("HTTPS")
                // 接口 HTTP 方法
                .setMethod("POST")
                .setAuthType("AK")
                .setStyle("ROA")
                // 接口 PATH
                .setPathname("/" + WorkspaceId + "/index/add_documents_to_index")
                // 接口请求体内容格式
                .setReqBodyType("json")
                // 接口响应体内容格式
                .setBodyType("json");
        return params;
    }

    /**
     * 追加以及添加到数据中心的文档到索引
     * @param client
     * @param indexId
     * @param workSpaceId
     * @param documentIds
     * @param categoryIds
     * @throws Exception
     */
    public static void AddDocumentsJob(com.aliyun.teaopenapi.Client client,String indexId,String workSpaceId,String documentIds, String categoryIds) throws Exception {
        com.aliyun.teaopenapi.models.Params params = apply.createSubmitIndexAddDocumentsJobApiInfo(workSpaceId);
        // query params
        java.util.Map<String, Object> queries = new java.util.HashMap<>();
        queries.put("IndexId", indexId);
        queries.put("SourceType", "DATA_CENTER_FILE");
        queries.put("DocumentIds", com.aliyun.openapiutil.Client.arrayToStringWithSpecifiedStyle(java.util.Arrays.asList(
                documentIds
        ), "DocumentIds", "json"));
        queries.put("CategoryIds", com.aliyun.openapiutil.Client.arrayToStringWithSpecifiedStyle(java.util.Arrays.asList(
                categoryIds
        ), "CategoryIds", "json"));
        // runtime options
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        com.aliyun.teaopenapi.models.OpenApiRequest request = new com.aliyun.teaopenapi.models.OpenApiRequest()
                .setQuery(com.aliyun.openapiutil.Client.query(queries));
        // 复制代码运行请自行打印 API 的返回值
        // 返回值为 Map 类型,可从 Map 中获得三类数据:响应体 body、响应头 headers、HTTP 返回的状态码 statusCode。
        HashMap<String,Object> response = (HashMap<String, Object>) client.callApi(params, request, runtime);
        System.out.println("AddDocumentsJob: " + response.get("statusCode"));
    }

}
  • 上传效果查看

图片.png

图片.png


四、更多参考

通过API上传文件

API参考地址

相关文章
|
25天前
|
Java Maven Windows
使用Java创建集成JACOB的HTTP服务
本文介绍了如何在Java中创建一个集成JACOB的HTTP服务,使Java应用能够调用Windows的COM组件。文章详细讲解了环境配置、动态加载JACOB DLL、创建HTTP服务器、实现IP白名单及处理HTTP请求的具体步骤,帮助读者实现Java应用与Windows系统的交互。作者拥有23年编程经验,文章来源于稀土掘金。著作权归作者所有,商业转载需授权。
使用Java创建集成JACOB的HTTP服务
|
7天前
|
JavaScript 前端开发 API
|
8天前
|
SQL 分布式计算 BI
Dataphin中集成SelectDB以支持报表分析和API查询
本文介绍了一家零售企业如何利用SelectDB进行BI分析及数据服务API的查询。通过Dataphin的数据集成、SQL研发等功能,将CRM、ERP等系统数据汇聚加工,并推送至SelectDB构建销售数据集市层,以支持报表分析及API查询。SelectDB具备实时、统一、弹性及开放特性,适用于多种实时分析场景。文章详细描述了在Dataphin中集成SelectDB的整体方案、数据源配置、数据集成、数据开发及数据服务流程。
|
9天前
|
编解码 Linux 开发工具
Linux平台x86_64|aarch64架构RTMP推送|轻量级RTSP服务模块集成说明
支持x64_64架构、aarch64架构(需要glibc-2.21及以上版本的Linux系统, 需要libX11.so.6, 需要GLib–2.0, 需安装 libstdc++.so.6.0.21、GLIBCXX_3.4.21、 CXXABI_1.3.9)。
|
2月前
|
Java Devops 持续交付
探索Java中的Lambda表达式:简化代码,提升效率DevOps实践:持续集成与部署的自动化之路
【8月更文挑战第30天】本文深入探讨了Java 8中引入的Lambda表达式如何改变了我们编写和管理代码的方式。通过简化代码结构,提高开发效率,Lambda表达式已成为现代Java开发不可或缺的一部分。文章将通过实际例子展示Lambda表达式的强大功能和优雅用法。
|
2月前
|
缓存 安全 Java
Java服务器端技术:Servlet与JSP的集成与扩展
Java服务器端技术:Servlet与JSP的集成与扩展
22 3
|
2月前
|
存储 消息中间件 前端开发
Web2py框架下的神秘力量:如何轻松集成第三方API,让你的应用不再孤单!
【8月更文挑战第31天】在开发现代Web应用时,常需集成第三方服务如支付网关、数据存储等。本文将指导你使用Web2py框架无缝接入第三方API。通过实例演示从注册获取API密钥、创建控制器、发送HTTP请求到处理响应的全过程。利用`requests`库与Web2py的内置功能,轻松实现API交互。文章详细介绍了如何编写RESTful控制器,处理API请求及响应,确保数据安全传输。通过本教程,你将学会如何高效整合第三方服务,拓展应用功能。欢迎留言交流心得与建议。
36 1
|
1月前
|
图形学 iOS开发 Android开发
从Unity开发到移动平台制胜攻略:全面解析iOS与Android应用发布流程,助你轻松掌握跨平台发布技巧,打造爆款手游不是梦——性能优化、广告集成与内购设置全包含
【8月更文挑战第31天】本书详细介绍了如何在Unity中设置项目以适应移动设备,涵盖性能优化、集成广告及内购功能等关键步骤。通过具体示例和代码片段,指导读者完成iOS和Android应用的打包与发布,确保应用顺利上线并获得成功。无论是性能调整还是平台特定的操作,本书均提供了全面的解决方案。
110 0
|
2月前
|
API C# 开发框架
WPF与Web服务集成大揭秘:手把手教你调用RESTful API,客户端与服务器端优劣对比全解析!
【8月更文挑战第31天】在现代软件开发中,WPF 和 Web 服务各具特色。WPF 以其出色的界面展示能力受到欢迎,而 Web 服务则凭借跨平台和易维护性在互联网应用中占有一席之地。本文探讨了 WPF 如何通过 HttpClient 类调用 RESTful API,并展示了基于 ASP.NET Core 的 Web 服务如何实现同样的功能。通过对比分析,揭示了两者各自的优缺点:WPF 客户端直接处理数据,减轻服务器负担,但需处理网络异常;Web 服务则能利用服务器端功能如缓存和权限验证,但可能增加服务器负载。希望本文能帮助开发者根据具体需求选择合适的技术方案。
68 0
|
2月前
|
机器学习/深度学习 存储 监控
利用机器学习技术优化数据中心能效
【7月更文挑战第36天】在数据中心管理和运营中,能源效率已成为关键性能指标之一。随着能源成本的不断上升以及环境保护意识的增强,开发智能化、自动化的解决方案以降低能耗和提高能源利用率变得尤为重要。本文探讨了如何应用机器学习技术对数据中心的能源消耗进行建模、预测和优化,提出了一个基于机器学习的框架来动态调整资源分配和工作负载管理,以达到节能的目的。通过实验验证,该框架能够有效减少数据中心的能耗,同时保持服务质量。
下一篇
无影云桌面