此解决方案适用于使用 OAuth 2.0 的服务器到服务器通信 这是一个三步过程
- 使用 OAuth 2.0 进行身份验证
- 获取 com.google.api.services.tasks.Tasks 服务对象
- 获取所需的Task或TaskList
在此示例代码中,它使用域 ID“abc.com”,用户为“user1@abc.com”。对于 gmail 用户,请提供 gmailid (abc@gmail.com) 作为 consumerkey,并将“xoauth_requestor_id”保留为 gmailid
import com.google.api.client.http.*;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.tasks.*;
import com.google.api.client.auth.oauth.OAuthHmacSigner;
import com.google.api.client.auth.oauth.OAuthParameters;
public class GoogleConnection {
public Tasks setup() throws Exception {
com.google.api.services.tasks.Tasks tasks = null;
HttpRequestFactory httpRequestFactory = null;
HttpRequestInitializer httpRequestInitializer = null;
OAuthHmacSigner signer = new OAuthHmacSigner();
HttpTransport httpTransport = new NetHttpTransport();
OAuthParameters oauthParameters = new OAuthParameters();
final ArrayMap<String, Object> customKeys = new ArrayMap<String, Object>();
customKeys.add("xoauth_requestor_id", "user1@abc.com");
signer.clientSharedSecret = "secret_key_received_from_google";
oauthParameters.version = "2.0";
oauthParameters.consumerKey = "abc.com";
oauthParameters.signer = signer;
httpRequestFactory = createRequestFactory(httpTransport, oauthParameters, "20000", "20000");
httpRequestInitializer = httpRequestFactory.getInitializer();
tasks = new com.google.api.services.tasks.Tasks.Builder(httpTransport, new JacksonFactory(), httpRequestInitializer)
.setTasksRequestInitializer(new TasksRequestInitializer() {
@Override
public void initializeTasksRequest(TasksRequest<?> request) throws IOException {
@SuppressWarnings("rawtypes")
TasksRequest tasksRequest = (TasksRequest) request;
tasksRequest.setUnknownKeys(customKeys);
tasksRequest.setKey("keyapi_received_from_google_by_registering_your_app");
}
})
.setApplicationName("")
.build();
return tasks;
}
}
从任务列表中获取任务 实例化 GoogleConnection 类
public List<com.google.api.services.tasks.model.Task> getTasksFromTaskList(String taskListId) throws Exception {
com.google.api.services.tasks.Tasks tasksService = googleConnection.setup();
com.google.api.services.tasks.model.Tasks result = tasksService .tasks().list(taskListId).execute();
return result.getItems();
}