飞书开发API的调用

前言

飞书api文档并没有像钉钉一样直接给出对应的api代码实现,而是给出了接口url和所需参数,通过postman是可以很好的验证,单项目中获取结果还是得用代码实现

<1>以飞书 获取单个部门api 为例,看看飞书api

当前飞书java jdk 版本1.0.17-rc2,依赖如下:

        <!-- https://mvnrepository.com/artifact/com.larksuite.oapi/larksuite-oapi -->
        <dependency>
            <groupId>com.larksuite.oapi</groupId>
            <artifactId>larksuite-oapi</artifactId>
            <version>1.0.17-rc2</version>
        </dependency>

官方api链接: 飞书根据部门id获取当个部门信息之后官方文档若有改动,请以官方为准
文档大致内容:

请求

在这里插入图片描述

请求头

在这里插入图片描述

路径参数

在这里插入图片描述

查询参数

在这里插入图片描述

1、路径参数必须拼接到请求url后面,下面代码会见到

2、查询参数有user_id_type,非必填,默认open_id,这里要注意,不是根据用户id去查,而是返回的部门领导人id类型是user_id还是open_id
3、查询参数department_id_type,非必填,默认open_department_id,也就是用open_department_id还是用department_id去获取用不详情

<2>api的调用方式

1.httpclient发请求

public static String hcGetDp(String department_id) throws HttpException, IOException {
        //请求接口
        String url = "https://open.feishu.cn/open-apis/contact/v3/departments/";

        // 创建httpClient实例对象
        HttpClient httpClient = new HttpClient();
        // 设置httpClient连接主机服务器超时时间:20000毫秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(20000);
        // 创建GET请求方法实例对象

        //因为是路径参数,所以要直接拼接到url后面
        GetMethod getMethod = new GetMethod(url+department_id);

            NameValuePair nameValuePair = new NameValuePair();
            nameValuePair.setName("department_id_type");
            nameValuePair.setValue("department_id");

            NameValuePair[] nValue = new NameValuePair[1];
            nValue[0] = nameValuePair;

            getMethod.setQueryString(nValue);

        // 设置post请求超时时间
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 50000);
        getMethod.addRequestHeader("Content-Type", "application/json");
        getMethod.addRequestHeader("Authorization", "Bearer t-d5ea464c88c7b22d78a6d2f7613fdbfa7533199b");

        httpClient.executeMethod(getMethod);

        String result = getMethod.getResponseBodyAsString();
        getMethod.releaseConnection();
        return result;
    }

我对httpclient使用的也不是很多,参数我就原步照搬,因为看他底层方法有setQueryString(NameValuePair[] params),就直接这样写了,当然喜欢用httpclient的老哥,可以自行封装,可以设置更专业的写法分享出来

2.hutool工具来发请求

    private static void hutoolGetDp(String department_id) {
        Map<String, Object> body = new HashMap<>();
//        body.put("department_id_type", "open_department_id");
        body.put("department_id_type", "department_id");
        String token = "Bearer " + "t-xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
        String url = "https://open.feishu.cn/open-apis/contact/v3/departments/";
        
        String  result =  HttpRequest.get(url+department_id).header("Authorization", token ).form(body).execute().body();
        
        System.out.println("================响应结果=================");
        System.out.println(result);
    }

hutool写完后眼前一亮,够简单够直接,但是得去获取Authorization

3.官方通用api

    private static void openApiGetDp(String department_id) throws Exception {
        Map<String, Object> body = new HashMap<>();
//        body.put("department_id_type", "open_department_id");
        body.put("department_id_type", "department_id");

        Request<Map<String, Object>, Map<String, Object>> request = Request.newRequest("contact/v3/departments/"+department_id,
                "GET", AccessTokenType.Tenant, null, new HashMap<>(),Request.setQueryParams(body));
        Response<Map<String, Object>> response = Api.send(config, request);

        System.out.println("================响应结果=================");
        System.out.println(Jsons.DEFAULT_GSON.toJson(response));
    }

官方参数说明;

// httpPath:API路径(`open-apis/`之后的路径),例如:https://domain/open-apis/contact/v3/users/:user_id,则 httpPath:"contact/v3/users/:user_id"
    // httpMethod: GET/POST/PUT/BATCH/DELETE
    // accessTokenType:API使用哪种访问凭证枚举,取值范围:AccessTokenType.App/AccessTokenType.Tenant/AccessTokenType.User,例如:AccessTokenType.Tenant
    // input:请求体(可能是 new FormData()(文件上传)),如果不需要请求体(例如一些GET请求),则传:null
    // output:响应体(output := response["data"])
    // requestOptFns:扩展函数,一些不常用的参数封装,如下:
    // Request.setPathParams(map[string]object{"user_id": 4}):设置URL Path参数(有:前缀)值,当httpPath="contact/v3/users/:user_id"时,请求的URL="https://{domain}/open-apis/contact/v3/users/4"
    // Request.setQueryParams(map[string]object{"age":4,"types":[1,2]}):设置 URL query,会在url追加?age=4&types=1&types=2
    // Request.setResponseStream(),设置响应的是否是流,例如下载文件,这时:output的类型需要实现 java.io.OutputStream 接口
    // Request.setNotDataField(),设置响应的是否 没有`data`字段,业务接口都是有`data`字段,所以不需要设置
    // Request.setTenantKey("TenantKey"),以`应用商店应用`身份,表示使用`tenant_access_token`访问API,需要设置
    // Request.setUserAccessToken("UserAccessToken"),表示使用`user_access_token`访问API,需要设置
    // Request.setTimeout(int time, TimeUnit timeUnit),设置请求超时的时间

官方api看起来不错,我项目中也有使用,当然POST写法相对简单点,我就不列举POST了,他的Authorization直接用AccessTokenType.Tenant这个进行设置,正常来说传进去config,就已经包含APP_ID和APP_SECRET是可以直接获取t_token的,所以这里只用传config,代码如下:

    //应用Id
    private static final String APP_ID = "cli_aaaaaaaaaaaaa";
    //应用密钥
    private static final String APP_SECRET = "xxxxxxxxxxxxxxxxxxxxxxxx";
    
    // for Cutome APP(自建应用)
    private static final AppSettings appSettings = Config.createInternalAppSettings(APP_ID,APP_SECRET,null,null);
    private static final Config config = new Config(Domain.FeiShu, appSettings, new RStore());

new RStore()我就不贴出来了,其实就是自定义RStore类去实现官方api 的IStore接口

4.官方正在研发的服务api

    private static void getDp(String department_id) throws Exception {
        ContactService contactService = new ContactService(config);
        Response<DepartmentPatchResult> response = contactService.getDepartments().get(Request.setTenantKey("Tenant Key")).setDepartmentId(department_id).setDepartmentIdType("department_id").execute();

        System.out.println("===================响应结果==================");
        System.out.println(response.getRequestID());
        System.out.println(response.getHTTPStatusCode());
        System.out.println(Jsons.DEFAULT_GSON.toJson(response));
    }

可以看出其实是对通用api的一个封装,我也在使用,larksuite-oapi的jar包里面有,没有又可能还在研发中,或者jar包版本过低
在这里插入图片描述

总结

官方服务api更新得非常快,最开始只有几个,现在都有很多了,大部分需求应该够用的,之后有可能像钉钉一样,一段文档,一段api,也可以提前适应一下,最终趋势应该这个服务型api
<如代码有错误请指出,有可能是测试代码和表述代码命名不一样>

  • 5
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值