我的总体目标是能够自动下载每日report using the bing ads API。为此,我需要authenticate with OAuth(旧的PasswordAuthentication方法不起作用,因为我有一个新的微软帐户)。我手动完成了“授权代码授权流程”并成功授权。问题是:
Here's an example desktop app using OAuth
有人知道吗
SOLUTION:
如@eric urban所述,只需手动授权一次。之后,刷新令牌就可以了。 (看看示例桌面应用程序并不是很明显!)
我写了一个类来处理所有OAuth的东西,并将刷新令牌保存到文件
public class OAuthRefreshToken {
private static String refreshTokenFileName = "./bingAdsRefreshToken.txt";
private static String ClientId = "XXXXX";
private final OAuthDesktopMobileAuthCodeGrant oAuthDesktopMobileAuthCodeGrant = new OAuthDesktopMobileAuthCodeGrant(ClientId);
private String refreshToken;
public OAuthRefreshToken() {
oAuthDesktopMobileAuthCodeGrant.setNewTokensListener(new NewOAuthTokensReceivedListener() {
@Override
public void onNewOAuthTokensReceived(OAuthTokens newTokens) {
String refreshTime = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.format(new java.util.Date());
refreshToken = newTokens.getRefreshToken();
System.out.printf("Token refresh time: %s\n", refreshTime);
writeRefreshTokenToFile();
}
});
getRefreshTokenFromFile();
refreshAccessToken();
}
public OAuthRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
writeRefreshTokenToFile();
}
public OAuthDesktopMobileAuthCodeGrant getoAuthDesktopMobileAuthCodeGrant() {
return oAuthDesktopMobileAuthCodeGrant;
}
private void refreshAccessToken(){
oAuthDesktopMobileAuthCodeGrant.requestAccessAndRefreshTokens(refreshToken);
}
private void getRefreshTokenFromFile(){
try {
refreshToken = readFile(refreshTokenFileName, Charset.defaultCharset());
} catch (IOException e) {
e.printStackTrace();
}
}
private static String readFile(String path, Charset encoding)
throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
private void writeRefreshTokenToFile(){
File refreshTokenFile = new File(refreshTokenFileName);
try {
FileWriter f2 = new FileWriter(refreshTokenFile);
f2.write(refreshToken);
f2.close();
} catch (IOException e) {
e.printStackTrace();
return;
}
System.out.printf("New refresh token: %s\n", refreshToken);
System.out.printf("Stored Safely in: %s\n", refreshTokenFileName);
}
}
在您的应用中使用它,如:
final OAuthRefreshToken oAuthRefreshToken = new OAuthRefreshToken();
final OAuthDesktopMobileAuthCodeGrant oAuthDesktopMobileAuthCodeGrant = oAuthRefreshToken.getoAuthDesktopMobileAuthCodeGrant();
答案 0 :(得分:1)
您是正确的,需要事先征得用户同意(一次)。此后,您可以使用刷新令牌在没有用户交互的情况下请求其他访问令牌。有关使用Bing Ads Java SDK的授权代码授权流程的详细信息,请参阅Getting Started Using Java with Bing Ads Services。这有帮助吗?
答案 1 :(得分:0)
刷新令牌不应该很快到期,它们通常是永久性的或持续很长时间。但是,如果您请求过多,这些可能会被撤销或失效。我相信当你请求超过25种不同的刷新令牌时,它们的旧版本开始变得无效。