Примеры API инструментов тестирования URL-адресов Search Console

Образец кода часто является самым простым способом научиться использовать API. Чтобы получить ссылки на примеры API инструментов тестирования URL-адресов Search Console, выберите язык программирования ниже.

В примерах используются клиентские библиотеки Google API.

Если на странице примеров библиотеки еще нет образца для API инструментов тестирования URL-адресов Search Console, вы все равно можете использовать эту библиотеку и адаптировать примеры, предоставленные для другого Google API.

Идти

Нет примеров Go специально для этой версии API инструментов тестирования URL-адресов Search Console.

Однако вы можете адаптировать один из других примеров Go .

Джава

package codesamples;

import com.google.api.client.http.ByteArrayContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import java.io.IOException;
import org.json.JSONException;
import org.json.JSONObject;

/** Example of Java client calling Search Console URL Testing Tools API */
public final class MftExample {
  public static void main(String[] args) {
    try {
      HttpTransport httpTransport = new NetHttpTransport();
      HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
      GenericUrl url = new GenericUrl(
          "https://searchconsole.googleapis.com/v1/urlTestingTools/mobileFriendlyTest:run"
          + "?key={YOUR_API_KEY}");
      JSONObject json = new JSONObject();
      json.put("url", "https://www.google.com/");
      String requestBody = json.toString();
      HttpRequest request = requestFactory.buildPostRequest(
          url, ByteArrayContent.fromString("application/json", requestBody));
      System.out.println("request was: " + requestBody);
      HttpResponse httpResponse = request.setReadTimeout(70000).execute();

      String content = httpResponse.parseAsString();
      System.out.println(content);
    } catch (IOException | JSONException ex) {
      ex.printStackTrace();
    }
  }
}

JavaScript

<!DOCTYPE html>
<html>
<head>
<script>
function listMobileFriendlyIssues(responseJson) {
  var resultEl = document.getElementById('result');
  if (responseJson.mobileFriendlyIssues) {
    resultEl.innerHTML += "Mobile friendly issues:<br>";
    responseJson.mobileFriendlyIssues.forEach(function(issue) {
        resultEl.innerHTML += "<li>" + issue.rule + "</li>"});
  } else {
    resultEl.innerHTML += "No mobile friendliness issues found!";
  }
}
function runInspection() {
  var apiUrl = 'https://searchconsole.googleapis.com/v1/urlTestingTools/mobileFriendlyTest:run?key={YOUR_API_KEY}';
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.open("POST", apiUrl);
  xmlhttp.setRequestHeader("Content-Type", "application/json");
  xmlhttp.send(
      '{"url": "' + document.getElementById("url").value + '", "requestScreenshot": true}');
  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4) {
      var responseJson = JSON.parse(this.responseText);
      if (this.status == 200) {
        listMobileFriendlyIssues(responseJson);
        document.getElementById('image').src =
            "data:" + responseJson.screenshot.mimeType + ';base64,' + responseJson.screenshot.data;
      } else {
        document.getElementById('result').innerHTML += "An error occured!<br>Error code: "
            + responseJson.error.code + "<br>Error message: " + responseJson.error.message;
      }
    }
  };
};
</script>
</head>
<body>
<br>URL: <input type="text" id="url" size="40">
<br><br><button onclick="runInspection();">Fetch</button>
<br><br>Result:
<div id="result" style="border: solid thin black; height:5em; overflow:auto;"></div>
Screenshot:
<img id="image" style="border: solid thin black;"/>
</body>
</html>

PHP

Нет примеров PHP специально для этой версии API инструментов тестирования URL-адресов Search Console.

Однако вы можете адаптировать один из других примеров PHP .

питон

"""Example of Python client calling Search Console URL Testing Tools API."""
import urllib
import urllib2

api_key = '{YOUR_API_KEY}'
request_url = 'http://www.google.com/'
service_url = 'https://searchconsole.googleapis.com/v1/urlTestingTools/mobileFriendlyTest:run'
params = {
    'url': request_url,
    'key': api_key,
}
data = urllib.urlencode(params)
content = urllib2.urlopen(url=service_url, data=data).read()
print(content)

Рубин

Не существует примеров Ruby специально для этой версии API инструментов тестирования URL-адресов Search Console.

Однако вы можете адаптировать один из других примеров Ruby .