我想使用带有 javafx 的嵌入式浏览器对用户进行身份验证。我可以获得 twitter 给我的 PIN(字符串),但是当我尝试创建 AccesToken 时,它没有正确创建它。(我无法获得我的令牌或 tokenSecret,两者都为空)。
这是我的代码:
public static void main(String[] args)
{
Application.launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception
{
primaryStage.setTitle("WebView test");
WebView browser = new WebView();
engine = browser.getEngine();
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
requestToken = twitter.getOAuthRequestToken();
String url = requestToken.getAuthorizationURL();
engine.load(url);
engine.getLoadWorker().stateProperty().addListener(new ChangeListener<State>()
{
public void changed(ObservableValue ov, State oldState, State newState)
{
if (newState==State.SUCCEEDED && engine.getLocation().equals("https://api.twitter.com/oauth/authorize"))
{
String pin = engine.getDocument().getDocumentElement().getElementsByTagName("code").item(0).getTextContent();
printAccesToken(pin);
}
}
});
StackPane sp = new StackPane();
sp.getChildren().add(browser);
Scene root = new Scene(sp);
primaryStage.setScene(root);
primaryStage.show();
}
private void printAccesToken(String pin)
{
AccessToken accessToken = null;
try
{
accessToken = twitter.getOAuthAccessToken(requestToken, pin);
}
catch (TwitterException e)
{
e.printStackTrace();
}
System.out.println(accessToken.getToken());
}
/*------------------------------------------------------------------*\
|* Attributs Private *|
\*------------------------------------------------------------------*/
private WebEngine engine;
private Twitter twitter;
private RequestToken requestToken;
private static final String CONSUMER_KEY = "xxx";
private static final String CONSUMER_SECRET = "xxx";
我基于 twitter4j 提供的代码示例,据我所知,我正在做完全相同的事情,只是我得到的字符串不是通过键盘输入的,我直接从浏览器中得到它......
http://twitter4j.org/en/code-examples.html
基于示例 #7