我正在尝试创建一个java程序,它将搜索Box Storage中的某些文件。为此,我尝试使用Box Java SDK,并在Box中创建了一个应用程序(https://app.box.com/developers/services)。
当我使用开发人员令牌时,我能够遍历我的盒子父/子文件夹。由于此令牌在60分钟内有效,我想以编程方式检索和设置令牌。当我查看手册时,它会手动调用api来获取这些令牌。
我尝试了以下代码..
BoxAPIConnection api = new BoxAPIConnection(clientid,clientsecret);
String accesstoken = api.getAccessToken();
String refreshtoken = api.getRefreshToken();
我不想向用户抛出一个框登录页面,并希望将该程序作为守护程序运行,该守护程序将搜索文件并吐出一些报告文本文件。
感谢您的帮助。
答案 0 :(得分:0)
如果使用state.conf文件,您将能够以编程方式刷新令牌/ refres_token对,而无需获取身份验证代码。这是我使用的代码段:
private static BoxAPIConnection getBoxAPIConnection(String client_id, String client_secret, String token, String refresh_token, String stateConfPath) {
String state = null;
try {
logger.info("Getting state.conf: " + stateConfPath + "/state.conf");
InputStream fis = new FileInputStream(stateConfPath + "/state.conf");
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(isr);
state = br.readLine();
}
catch (FileNotFoundException f) {
try {
// create file if it doesn't exist
PrintWriter writer = new PrintWriter(stateConfPath + "/state.conf", "UTF-8");
writer.println("");
writer.close();
}
catch (Exception w) {
logger.fatal("Exception", w);
}
}
catch (IOException e) {
logger.fatal("IOException", e);
}
BoxAPIConnection api = null;
//if (null == state || "".equals(state)) {
if (!token.equals("") && !refresh_token.equals("")) {
api = new BoxAPIConnection(client_id, client_secret, token, refresh_token);
} else {
logger.info("Restoring state..." + state);
api = BoxAPIConnection.restore(client_id, client_secret, state);
if (api.needsRefresh()) { // this is not a reliable call. It can still throw a 401 below
logger.info("api refreshing...");
api.refresh();
}
else {
logger.info("api good...");
}
}
return api;
}
答案 1 :(得分:0)
可以通过代码管理Box登录。
使用以下代码,每次都更新实际的访问权限和刷新令牌。
String accessToken = // access token from DB/property
String refreshToken = // refresh token from DB/property
String boxClientId = // client id from DB/property
String boxClientSecret = // client secret from DB/property
try {
BoxAPIConnection api = new BoxAPIConnection(boxClientId, boxClientSecret, accessToken, refreshToken);
api.addListener(new BoxAPIConnectionListener() {
@Override
public void onRefresh(BoxAPIConnection api) {
String newAccessToken = api.getAccessToken();
String newrefreshToken = api.getRefreshToken();
// update new access and refresh token in DB/property
}
@Override
public void onError(BoxAPIConnection api, BoxAPIException error) {
LOGGER.error("Error in Box account details. " + error.getMessage());
}
});
LOGGER.debug("Completed Box authentication");
} catch (Exception e) {
LOGGER.error("Error in Box authentication. Error msg : " + e.getMessage());
}