1

我想在 android 中集成 google photos api,我已经完成了 google 登录过程,但我无法获取访问令牌,因为我在传递参数时在 FixedCredentialsProvider.create 方法中遇到错误。

PhotosLibrarySettings settings =
     PhotosLibrarySettings.newBuilder()
    .setCredentialsProvider(
        FixedCredentialsProvider.create(/ Add credentials here. /)) 
    .build();

try (PhotosLibraryClient photosLibraryClient =
    PhotosLibraryClient.initialize(settings)) {

    // Create a new Album  with at title
    Album createdAlbum = photosLibraryClient.createAlbum("My Album");

    // Get some properties from the album, such as its ID and product URL
    String id = album.getId();
    String url = album.getProductUrl();

} catch (ApiException e) {
    // Error during album creation
}
4

1 回答 1

1

我能够找到问题的解决方案

UserCredentials.newBuilder()
            .setClientId("your client id")
            .setClientSecret("your client secret")
            .setAccessToken("Access Token")
            .build()

您可以将此 UserCredentials 对象传递给 FixedCredentialsProvider.create())

使用获取访问令牌

val client = OkHttpClient()
            val requestBody = FormEncodingBuilder()
                    .add("grant_type", "authorization_code")
                    .add("client_id", "")
                    .add("client_secret", "")
                    .add("redirect_uri", "")
                    .add("code", "yourweb server id)
                    .build()
            val request = Request.Builder()
                    .url("https://www.googleapis.com/oauth2/v4/token")
                    .post(requestBody)
                    .build()
            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(request: Request, e: IOException) {

                }

                @Throws(IOException::class)
                override fun onResponse(response: Response) {
                    try {
                        val jsonObject = JSONObject(response.body().string())

                        mTokenExpired = SystemClock.elapsedRealtime() + jsonObject.optLong("expires_in") * 1000

                        accessTokenObservable.postValue(Resource.success("",jsonObject.optString("access_token")))


                    } catch (e: JSONException) {
                        e.printStackTrace()
                    }

                }
            })

https://github.com/erickogi/AndroidGooglePhotosApi

希望能帮助到你

于 2019-02-05T11:54:22.400 回答