Пакет запросов API индексации Google в Java - PullRequest
0 голосов
/ 21 января 2019

У меня вопрос по API индексации Google.Я младший разработчик.TT

Я использую API индексации в исходном коде Java.Текущий вызов API был успешным при индексировании запросов для одного сайта (без пакета).Но я не могу сделать запрос партии.

https://developers.google.com/api-client-library/java/google-api-java-client/batch

Не следуйте примеру источника на верхней странице.Страница слишком бедна для объяснения.

https://productforums.google.com/forum/#!topic/webmasters/L6yVB7iq1os;context-place=topicsearch/indexing$20api$20request$20batch

Пример источника на ответе выше страницы также тот же.

Приведенный выше источник не находит вставкуметод.Вы можете мне помочь?

Ниже мой источник.


import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.batch.BatchRequest;
import com.google.api.client.googleapis.batch.json.JsonBatchCallback;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.http.*;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.Lists;
import com.google.api.services.indexing.v3.Indexing;
import com.google.api.services.indexing.v3.model.UrlNotification;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;

public class Main {
    public static List<HttpResponse> addedCalendarsUsingBatch = Lists.newArrayList();
    public static final String appName = "appName";
    private static com.google.api.services.calendar.Calendar client;

    public static void main(String[] args) {

        try {
            Main main = new Main();
            main.accessToken();

        } catch (Exception e) {

        }

    }

    public void accessToken() {
        try {
            HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();

            String scopes = "https://www.googleapis.com/auth/indexing";
            String endPoint = "https://indexing.googleapis.com/v3/urlNotifications:publish";

            JsonFactory jsonFactory = new JacksonFactory();

            // service_account_file.json is the private key that you created for your service account.
            File file = new File("/path/key.json");
            InputStream in = new FileInputStream(file);

            GoogleCredential credentials =
                    GoogleCredential.fromStream(in, httpTransport, jsonFactory)
                            .createScoped(Collections.singleton(scopes));

            GenericUrl genericUrl = new GenericUrl(endPoint);
            HttpRequestFactory requestFactory = httpTransport.createRequestFactory();

            // Define content here. The structure of the content is described in the next step.
            String content = "{"
                    + "\"url\": \"indexing URL Address\","
                    + "\"type\": \"URL_UPDATED\","
                    + "}";

            HttpRequest request =
                    requestFactory
                            .buildPostRequest(genericUrl, ByteArrayContent.fromString("application/json", content));

            credentials.initialize(request);
            HttpResponse response = request.execute();

            /**
             * Success so far. Problems from below
             * Batch start
             *
             * */

            String batchEndpoint = "https://indexing.googleapis.com/batch";
            GenericUrl batchGenericUrl = new GenericUrl(batchEndpoint);

            BatchRequest batch = new BatchRequest(httpTransport, httpRequestInitializer);
            batch.setBatchUrl(new GenericUrl(batchEndpoint));

            // Google Sample batch source
            // https://productforums.google.com/forum/#!topic/webmasters/L6yVB7iq1os;context-place=topicsearch/indexing$20api$20request$20batch
            Indexing client = Indexing.builder(transport, jsonFactory, credential).setApplicationName("BatchExample/1.0").build();
            BatchRequest batch = client.batch();

            UrlNotification entry1 = new UrlNotification().setUrl("http://foo.com/");
            client.urlNotifications().insert(entry1).queue(batch, callback);

            UrlNotification entry2 = new UrlNotification().setUrl("http://foo.com/page2");
            client.urlNotifications().insert(entry2).queue(batch, callback);

            batch.execute();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

1 Ответ

0 голосов
/ 20 июня 2019

Вам нужно использовать client.urlNotifications().publish(unf).queue(batch, callback); вместо вставки.Пример рабочего кода для вашей справки.

private static void requestBatchIndex(List<String> urls) throws Exception {
    String scopes = "https://www.googleapis.com/auth/indexing";
    String endPoint = "https://indexing.googleapis.com/v3/urlNotifications:publish";

    JsonFactory jsonFactory = new JacksonFactory();
    HttpTransport httpTransport = new NetHttpTransport();

    // service_account_file.json is the private key that you created for
    // your service account.
    InputStream in = FileUtils.openInputStream(new File("src/main/resources/service_account_file.json"));

    GoogleCredential credentials = GoogleCredential.fromStream(in, httpTransport, jsonFactory).createScoped(Collections.singleton(scopes));

    JsonBatchCallback<PublishUrlNotificationResponse> callback = new JsonBatchCallback<PublishUrlNotificationResponse>() {

        public void onSuccess(PublishUrlNotificationResponse res, HttpHeaders responseHeaders) {
            try {
                System.out.println(res.toPrettyString());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
            System.out.println("Error Message: " + e.getMessage());
        }
    };

    IndexingRequestInitializer iri = new IndexingRequestInitializer();
    Indexing client = new Indexing(httpTransport, jsonFactory, credentials);
    BatchRequest batch = client.batch();
    batch.setBatchUrl(new GenericUrl("https://indexing.googleapis.com/batch"));

    for (String url : urls) {
        UrlNotification unf = new UrlNotification();
        unf.setUrl(url);
        unf.setType("URL_UPDATED");
        client.urlNotifications().publish(unf).queue(batch, callback);
    }

    batch.execute();
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...