使用Java调用Confluence的REST API

Confluence REST API Documentation

API接口说明文档传送门

接口访问说明

Confluence的REST API访问一样采用http访问的形式,但最主要的是接口的鉴权,本文使用的是用户名+密码的鉴权方式。当然Confluence还提供令牌的鉴权方式,只是需要自己通过界面申请。闲话少叙,直接放代码

public class Test {
    public static void main(String[] args) throws UnsupportedEncodingException {
        //用户名
        String name = "xxxxxx";
        //密码
        String password = "xxxxxxx";
        String authString = name + ":" + password;
        byte[] authEncBytes = Base64.encodeBase64(authString.getBytes("utf-8"));
        String authStringEnc = new String(authEncBytes);
        //注意加空格
        System.out.println("Basic " + authStringEnc);
    }
}

使用PostMan测试
在这里插入图片描述

完整代码

public class Test {
    private static String path = "xxxxxxxxxxx";

    
    public static void main(String[] args) throws UnsupportedEncodingException {
        //用户名
        String name = "xxxxxxx";
        //密码
        String password = "xxxxxxxx";
        String authString = name + ":" + password;
        byte[] authEncBytes = Base64.encodeBase64(authString.getBytes("utf-8"));
        String authStringEnc = new String(authEncBytes);
        //注意加空格
        System.out.println("Basic " + authStringEnc);
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            URL realUrl = new URL(path);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            connection.setRequestProperty("Accept", "application/json; charset=utf-8");
            connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        System.out.println(result.toString());
    }
}

上述代码采用的是Get提交方式,如果REST API需要Post的提交方式,可将代码中URL连接改成Post方式。当然,更推荐使用HttpClient或OkHttp等轮子。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值