减少加载gmail标头所需的时间

时间:2019-01-10 10:55:35

标签: java google-api gmail-api

我正在Web应用程序上呈现Gmail标题,例如FROM,SUBJECT和DATE(每页10封邮件)。 但是根据gmail的api,我们首先必须首先调用messeses.list以获取消息ID的列表,然后在这些ID的每一个上调用message.get以获取实际的标头。 / p>

所以第一步,我的代码是这样的,

String link = "https://www.googleapis.com/gmail/v1/users/" + fromMail + "/messages/?labelIds=" + mailFolder + "&maxResults=10";

//Making oauth request to get message id's
JSONObject respObj = GmailUtil.requestGetUrl(link, access_token);
if (respObj.has("messages")) msgArray = respObj.getJSONArray("messages");

if (!respObj.has("nextPageToken")) isEmptyCurrentPage = true;

// 2nd step. Iterating through each id's to get the headers.
for (int i = 0; i < msgArray.length(); i++) {
    JSONObject jsonObj = msgArray.getJSONObject(i);
    String msgId = jsonObj.getString("threadId");

    String urlLink = "https://www.googleapis.com/gmail/v1/users/" + fromMail + "/messages/" + msgId + "?labelIds=" + mailFolder + "&format=metadata&metadataHeaders=id&metadataHeaders=subject&metadataHeaders=From&metadataHeaders=Date";
    JSONObject msgResult = GmailUtil.requestGetUrl(urlLink, access_token);

    JSONObject jObj = new JSONObject();
    jObj.put("checkBoxVal", false);
    jObj.put("date", getHeader(msgResult, "date") != null ? UtilityClass.mailBoxDateFormatter1.format(new MailDateFormat().parse(getHeader(msgResult, "date"))) : "");
    jObj.put("from", getHeader(msgResult, "from"));
    jObj.put("fromEmail", UtilityClass.extractEmailIdFromString(getHeader(msgResult, "from")));
    jObj.put("messageId", msgId);
    }

现在,此过程至少需要6到10秒才能执行。如何优化此源代码以更快地执行。谢谢。

1 个答案:

答案 0 :(得分:1)

这是API的工作方式。首先,您会收到一条消息列表,如果要获取消息的详细信息,则必须发送message.get。 Api还具有标准的响应时间,实际上您无法加快速度。

关于优化代码,我建议您使用Google apis编写的Google apis Java客户端库进行研究。 Quick start java

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.gmail.model.Label;
import com.google.api.services.gmail.model.ListLabelsResponse;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;

public class GmailQuickstart {
    private static final String APPLICATION_NAME = "Gmail API Java Quickstart";
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    private static final String TOKENS_DIRECTORY_PATH = "tokens";

    /**
     * Global instance of the scopes required by this quickstart.
     * If modifying these scopes, delete your previously saved tokens/ folder.
     */
    private static final List<String> SCOPES = Collections.singletonList(GmailScopes.GMAIL_LABELS);
    private static final String CREDENTIALS_FILE_PATH = "/credentials.json";

    /**
     * Creates an authorized Credential object.
     * @param HTTP_TRANSPORT The network HTTP Transport.
     * @return An authorized Credential object.
     * @throws IOException If the credentials.json file cannot be found.
     */
    private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
        // Load client secrets.
        InputStream in = GmailQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

        // Build flow and trigger user authorization request.
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
                .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
                .setAccessType("offline")
                .build();
        LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
        return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
    }

    public static void main(String... args) throws IOException, GeneralSecurityException {
        // Build a new authorized API client service.
        final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        Gmail service = new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
                .setApplicationName(APPLICATION_NAME)
                .build();

        // Print the labels in the user's account.
        String user = "me";
        ListLabelsResponse listResponse = service.users().labels().list(user).execute();
        List<Label> labels = listResponse.getLabels();
        if (labels.isEmpty()) {
            System.out.println("No labels found.");
        } else {
            System.out.println("Labels:");
            for (Label label : labels) {
                System.out.printf("- %s\n", label.getName());
            }
        }
    }
}