public static void main(String[] args) { /* * 初始化 OAuth ,设置 app key 和 对应的 secret 重复测试时,可直接对access * token等鉴权参数赋值,以便省略授权过程(完成一次正常的授权过程即可手动设置) */ init(oAuth); /* * -----------------------------------------授权流程 * begin-------------------------------------------------- */ // 自定制http连接管理器 QHttpClient qHttpClient = new QHttpClient(2, 2, 5000, 5000, null, null); OAuthV2Client.setQHttpClient(qHttpClient); // 调用外部浏览器,请求用户授权,并读入授权码等参数 openBrowser(oAuth); // 检查是否正确取得授权码 if (oAuth.getStatus() == 2) { System.out.println("Get Authorization Code failed!"); return; } // 换取access token oAuth.setGrantType("authorize_code"); try { OAuthV2Client.accessToken(oAuth); } catch (Exception e1) { e1.printStackTrace(); } // 检查是否正确取得access token if (oAuth.getStatus() == 3) { System.out.println("Get Access Token failed!"); return; } qHttpClient.shutdownConnection(); /* * -----------------------------------------授权流程 * end-------------------------------------------------- */ // 执行测试列表 try { new TestOAuthV2AuthorizeCodeGrantAndAPI().testList(); } catch (Exception e) { e.printStackTrace(); } }
private static void openBrowser(OAuthV2 oAuth) { String authorizationUrl = OAuthV2Client.generateAuthorizationURL(oAuth); // 调用外部浏览器 if (!java.awt.Desktop.isDesktopSupported()) { System.err.println("Desktop is not supported (fatal)"); System.exit(1); } java.awt.Desktop desktop = java.awt.Desktop.getDesktop(); if (desktop == null || !desktop.isSupported(java.awt.Desktop.Action.BROWSE)) { System.err.println("Desktop doesn't support the browse action (fatal)"); System.exit(1); } try { desktop.browse(new URI(authorizationUrl)); } catch (Exception e) { e.printStackTrace(); System.exit(1); } System.out.println( "Input the authorization information (eg: code=CODE&openid=OPENID&openkey=OPENKEY) :"); Scanner in = new Scanner(System.in); String responseData = in.nextLine(); in.close(); if (OAuthV2Client.parseAuthorization(responseData, oAuth)) { System.out.println("Parse Authorization Information Successfully"); } else { System.out.println("Fail to Parse Authorization Information"); return; } }