要解决"保存新凭据后,Google-oauth-java-client中的凭据存储为空"的问题,你可以使用以下代码示例:
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.auth.oauth2.StoredCredential;
import com.google.api.client.auth.oauth2.MemoryDataStoreFactory;
import com.google.api.client.util.store.DataStore;
import java.io.IOException;
public class CredentialStorageExample {
private static final String USER_ID = "user123";
public static void main(String[] args) throws IOException {
// 创建一个内存中的DataStore用于存储凭据
DataStore credentialDataStore = MemoryDataStoreFactory.getDefaultInstance()
.getDataStore(USER_ID);
// 创建一个新的凭据
Credential newCredential = new Credential(/*填写你的凭据参数*/);
// 将新凭据保存到存储中
credentialDataStore.set(USER_ID, new StoredCredential(newCredential));
// 从存储中获取凭据
StoredCredential storedCredential = credentialDataStore.get(USER_ID);
if (storedCredential != null && storedCredential.getAccessToken() != null) {
System.out.println("凭据存储成功:" + storedCredential.getAccessToken());
} else {
System.out.println("凭据存储为空");
}
}
}
在这个示例中,我们使用MemoryDataStoreFactory
创建一个内存中的数据存储credentialDataStore
用于存储凭据。然后,我们创建一个新的凭据newCredential
并将其保存到存储中。最后,我们从存储中获取凭据并检查是否成功保存。
请注意,这只是一个示例,你需要根据你的实际情况进行调整,例如使用适合你的凭据类型的Credential
构造函数,并根据需要调整存储凭据的方式。