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等轮子。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)