Сокращение времени, необходимого для загрузки заголовков Gmail - PullRequest
0 голосов
/ 10 января 2019

Я отображаю заголовки gmail, такие как FROM, SUBJECT и DATE, в моем веб-приложении (10 писем на страницу). Но в соответствии с API gmail сначала нам нужно вызвать messeses.list , чтобы сначала получить список идентификаторов сообщений, а затем вызвать message.get для каждого из них. идентификаторы, чтобы получить фактические заголовки.

Итак, для первого шага мой код такой,

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 голосов
/ 10 января 2019

Так работает API. Сначала вы получаете список сообщений, и если вам нужны подробности о сообщении, вы должны отправить message.get. Api также имеет стандартное время отклика, и вы не сможете ускорить его.

Что касается оптимизации вашего кода, я бы предположил, что вы изучите использование клиентской библиотеки Java apis Google, которая была написана Google для использования с их apis. Быстрый старт 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());
            }
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...