在Github上注册并获得授权令牌后,可以使用Android中的Github API进行登录并获取访问令牌。以下是实现该功能所需的代码示例(Java语言):
在Android项目的build.gradle文件中添加以下依赖项:
dependencies { implementation 'com.squareup.okhttp3:okhttp:3.12.0' implementation 'com.google.code.gson:gson:2.8.5' }
最初,需要创建Github授权网址以便用户进行授权。您可以将以下代码添加到活动的 onCreate 方法中:
String clientId = "YOUR_CLIENT_ID"; String clientSecret = "YOUR_CLIENT_SECRET"; String redirectUrl = "com.yourdomain.yourapp";
String authUrl = "https://github.com/login/oauth/authorize" + "?client_id=" + clientId + "&client_secret=" + clientSecret + "&redirect_uri=" + redirectUrl + "&scope=repo,user";
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)); startActivity(intent);
当用户在Github上授权应用程序时,系统会重定向用户到指定的“redirectUrl”,包括授权码。可以使用以下代码从重定向URL中检索此授权码:
@Override public void onResume() { super.onResume();
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(redirectUrl)) {
String code = uri.getQueryParameter("code");
if (code != null) {
retrieveAccessToken(code);
} else if (uri.getQueryParameter("error") != null) {
String error = uri.getQueryParameter("error");
String errorDescription = uri.getQueryParameter("error_description");
showErrorDialog(error + ": " + errorDescription);
}
}
}
private void retrieveAccessToken(String code) { // Request access token from Github API String clientId = "YOUR_CLIENT_ID"; String clientSecret = "YOUR_CLIENT_SECRET"; String redirectUri = "com.yourdomain.yourapp"; String url = "https://github.com/login/oauth/access_token" + "?client_id=" + clientId + "&client_secret=" + clientSecret + "&code=" + code + "&redirect_uri=" + redirectUri;
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.post(RequestBody.create(null, new byte[0