Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Google Cloud Platform proporciona una servidor de metadatos que conoce detalles acerca de tu instancia de App Engine, como el ID del proyecto al que pertenece, cuentas de servicio y los tokens usados por las cuentas de servicio. Puedes acceder a estos datos a través de solicitudes HTTP simples: no se requieren bibliotecas de cliente.
Esta página muestra cómo acceder a metadatos de instancia desde tu aplicación de entorno de ejecución de Java 8 implementada a través de llamadas HTTP a los extremos del servidor de metadatos adecuados.
Una forma muy útil de usar esta API es obtener el token de la cuenta de servicio y proporcionarlo como un token del portador en el encabezado de Autorización de una de las API de Google Cloud, para autenticar tu aplicación en ese servicio de API particular.
Consulta la documentación de la API de Google Cloud Translation para ver un ejemplo de cómo se usan estos tokens del portador.
Identificar qué extremo de metadatos usar
En la tabla siguiente, se enumeran los extremos en los que puedes realizar solicitudes HTTP para metadatos específicos. Se puede acceder al servidor de metadatos en http://metadata.google.internal.
Extremo de metadatos
Descripción
/computeMetadata/v1/project/numeric-project-id
El número de proyecto asignado a tu proyecto.
/computeMetadata/v1/project/project-id
El ID del proyecto asignado a tu proyecto.
/computeMetadata/v1/instance/zone
La zona en la que se está ejecutando la instancia.
Muestra el token de autenticación que puede usarse para autenticar tu aplicación en otras APIs de Google Cloud.
Por ejemplo, para recuperar tu ID del proyecto, envía una solicitud a http://metadata.google.internal/computeMetadata/v1/project/project-id.
Realizar solicitudes de metadatos
El código de muestra siguiente obtiene todos los metadatos disponibles para la instancia y los muestra, excepto para el token de la cuenta de servicio.
@SuppressWarnings("serial")// With @WebServlet annotation the webapp/WEB-INF/web.xml is no longer required.@WebServlet(name="Metadata",description="Metadata: Write info about GAE Standard",urlPatterns="/metadata")publicclassMetadataServletextendsHttpServlet{privatefinalString[]metaPath={"/computeMetadata/v1/project/numeric-project-id",// (pending)"/computeMetadata/v1/project/project-id","/computeMetadata/v1/instance/zone","/computeMetadata/v1/instance/service-accounts/default/aliases","/computeMetadata/v1/instance/service-accounts/default/email","/computeMetadata/v1/instance/service-accounts/default/","/computeMetadata/v1/instance/service-accounts/default/scopes",// Tokens work - but are a security risk to display// "/computeMetadata/v1/instance/service-accounts/default/token"};finalString[]metaServiceAcct={"/computeMetadata/v1/instance/service-accounts/{account}/aliases","/computeMetadata/v1/instance/service-accounts/{account}/email","/computeMetadata/v1/instance/service-accounts/{account}/scopes",// Tokens work - but are a security risk to display// "/computeMetadata/v1/instance/service-accounts/{account}/token"};privatefinalStringmetadata="http://metadata.google.internal";privateTemplateEnginetemplateEngine;// Use OkHttp from Square as it's quite easy to use for simple fetches.privatefinalOkHttpClientok=newOkHttpClient.Builder().readTimeout(500,TimeUnit.MILLISECONDS)// Don't dawdle.writeTimeout(500,TimeUnit.MILLISECONDS).build();// Setup to pretty print returned jsonprivatefinalGsongson=newGsonBuilder().setPrettyPrinting().create();privatefinalJsonParserjp=newJsonParser();// Fetch MetadataStringfetchMetadata(Stringkey)throwsIOException{Requestrequest=newRequest.Builder().url(metadata+key).addHeader("Metadata-Flavor","Google").get().build();Responseresponse=ok.newCall(request).execute();returnresponse.body().string();}StringfetchJsonMetadata(Stringprefix)throwsIOException{Requestrequest=newRequest.Builder().url(metadata+prefix).addHeader("Metadata-Flavor","Google").get().build();Responseresponse=ok.newCall(request).execute();// Convert json to prety jsonreturngson.toJson(jp.parse(response.body().string()));}@Overridepublicvoidinit(){// Setup ThymeLeafServletContextTemplateResolvertemplateResolver=newServletContextTemplateResolver(this.getServletContext());templateResolver.setPrefix("/WEB-INF/templates/");templateResolver.setSuffix(".html");templateResolver.setCacheTTLMs(Long.valueOf(1200000L));// TTL=20m// Cache is set to true by default. Set to false if you want templates to// be automatically updated when modified.templateResolver.setCacheable(true);templateEngine=newTemplateEngine();templateEngine.setTemplateResolver(templateResolver);}@OverridepublicvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)throwsIOException{StringdefaultServiceAccount="";WebContextctx=newWebContext(req,resp,getServletContext(),req.getLocale());resp.setContentType("text/html");Stringenvironment=(String)System.getProperties().get("com.google.appengine.runtime.environment");ctx.setVariable("production",environment);// The metadata server is only on a production systemif(environment.equals("Production")){TreeMap<String,String>m=newTreeMap<>();for(Stringkey:metaPath){m.put(key,fetchMetadata(key));if(key.contains("default/email")){defaultServiceAccount=m.get(key);}}ctx.setVariable("Metadata",m.descendingMap());m=newTreeMap<>();for(Stringkey:metaServiceAcct){// substitute a service account for {account}key=key.replace("{account}",defaultServiceAccount);m.put(key,fetchMetadata(key));}ctx.setVariable("sam",m.descendingMap());// Recursivly get all info about service accounts -- Note tokens are leftout by default.ctx.setVariable("rsa",fetchJsonMetadata("/computeMetadata/v1/instance/service-accounts/?recursive=true"));// Recursivly get all data on Metadata server.ctx.setVariable("ram",fetchJsonMetadata("/?recursive=true"));}templateEngine.process("index",ctx,resp.getWriter());}}
En el código de muestra, observa la marca para asegurarte de que la aplicación se está ejecutando en producción. Si la aplicación se está ejecutando localmente, no se mostrarán metadatos de las solicitudes.
Además, observa el uso del serializador/deserializador JSON de Google Gson, el cliente HTTP y HTTP2 de OkHttp, y el sistema de plantillas Thymeleaf. Estos no son necesarios, pero son bibliotecas muy útiles para tus propios proyectos.
Ejecución local
El servidor de metadatos está disponible para aplicaciones implementadas: no se admite la ejecución local en el servidor de desarrollo. Puedes agregar una marca de entorno a tu código para esperar resultados de metadatos, solo si la app se está ejecutando en producción, como se muestra en el código de muestra que se proporciona arriba:
Stringenvironment=(String)System.getProperties().get("com.google.appengine.runtime.environment");ctx.setVariable("production",environment);// The metadata server is only on a production systemif(environment.equals("Production")){...//show metadata results}
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-09-04 (UTC)"],[[["\u003cp\u003eGoogle Cloud Platform's metadata server provides details about your App Engine instance, accessible via simple HTTP requests to endpoints like \u003ccode\u003ehttp://metadata.google.internal\u003c/code\u003e, without needing client libraries.\u003c/p\u003e\n"],["\u003cp\u003eThe metadata server allows you to retrieve information such as project ID, zone, and service account details, including email and supported scopes.\u003c/p\u003e\n"],["\u003cp\u003eA key feature is the ability to retrieve a service account token from the metadata server, which can be used as a bearer token to authenticate your application with other Google Cloud APIs.\u003c/p\u003e\n"],["\u003cp\u003eAccessing the metadata server requires using native sockets like \u003ccode\u003ejava.net.HttpURLConnection\u003c/code\u003e and does not support the urlfetch service.\u003c/p\u003e\n"],["\u003cp\u003eThe metadata server is only accessible in a deployed environment; local development environments will not return metadata results, as shown in the example code's production check.\u003c/p\u003e\n"]]],[],null,["# Accessing Instance Metadata\n\nGoogle Cloud Platform provides a metadata server that knows details about your\nApp Engine instance, such as its containing project ID, service accounts, and\ntokens used by the service accounts. You can access this data using simple HTTP\nrequests: no client libraries are required.\n\nThis page shows how to access instance metadata from your deployed Java 8\nruntime application\nby making HTTP calls to the appropriate metadata server endpoints.\n| **Note:** Metadata access is currently read only: you cannot write your own metadata for an instance.\n\nOne useful way to use this API is to get the service account token and\nsupply it as a bearer token in the Authorization header of one of the Google\nCloud APIs, to authenticate your application to that particular API service.\nSee the [Google Cloud Translation API](/translate/docs/quickstart)\ndocumentation for an example of how these bearer tokens are used.\n\nIdentifying which metadata endpoint to use\n------------------------------------------\n\nThe following table lists the endpoints where you can make HTTP requests for\nspecific metadata. The metadata server is accessible at\n`http://metadata.google.internal`.\n\nFor example, to retrieve your project ID, send a request to\n`http://metadata.google.internal/computeMetadata/v1/project/project-id`.\n\nMaking metadata requests\n------------------------\n\n| **Important:** Access to the metadata server must use native sockets, such as those provided by `java.net.HttpURLConnection` or the native `url-stream-handler`. The metadata server does not support the [urlfetch](/appengine/docs/legacy/standard/java/issue-requests#using_urlfetch_in_a_java_8_app) service.\n\nThe following sample code gets all of the metadata available for the instance\nand displays it, except for the service account token. \n\n @SuppressWarnings(\"serial\")\n // With @WebServlet annotation the webapp/WEB-INF/web.xml is no longer required.\n @WebServlet(name = \"Metadata\", description = \"Metadata: Write info about GAE Standard\",\n urlPatterns = \"/metadata\")\n public class MetadataServlet extends HttpServlet {\n\n private final String[] metaPath = {\n \"/computeMetadata/v1/project/numeric-project-id\", // (pending)\n \"/computeMetadata/v1/project/project-id\",\n \"/computeMetadata/v1/instance/zone\",\n \"/computeMetadata/v1/instance/service-accounts/default/aliases\",\n \"/computeMetadata/v1/instance/service-accounts/default/email\",\n \"/computeMetadata/v1/instance/service-accounts/default/\",\n \"/computeMetadata/v1/instance/service-accounts/default/scopes\",\n // Tokens work - but are a security risk to display\n // \"/computeMetadata/v1/instance/service-accounts/default/token\"\n };\n\n final String[] metaServiceAcct = {\n \"/computeMetadata/v1/instance/service-accounts/{account}/aliases\",\n \"/computeMetadata/v1/instance/service-accounts/{account}/email\",\n \"/computeMetadata/v1/instance/service-accounts/{account}/scopes\",\n // Tokens work - but are a security risk to display\n // \"/computeMetadata/v1/instance/service-accounts/{account}/token\"\n };\n\n private final String metadata = \"http://metadata.google.internal\";\n private TemplateEngine templateEngine;\n\n // Use OkHttp from Square as it's quite easy to use for simple fetches.\n private final OkHttpClient ok = new OkHttpClient.Builder()\n .readTimeout(500, TimeUnit.MILLISECONDS) // Don't dawdle\n .writeTimeout(500, TimeUnit.MILLISECONDS)\n .build();\n\n // Setup to pretty print returned json\n private final Gson gson = new GsonBuilder()\n .setPrettyPrinting()\n .create();\n private final JsonParser jp = new JsonParser();\n\n // Fetch Metadata\n String fetchMetadata(String key) throws IOException {\n Request request = new Request.Builder()\n .url(metadata + key)\n .addHeader(\"Metadata-Flavor\", \"Google\")\n .get()\n .build();\n\n Response response = ok.newCall(request).execute();\n return response.body().string();\n }\n\n String fetchJsonMetadata(String prefix) throws IOException {\n Request request = new Request.Builder()\n .url(metadata + prefix)\n .addHeader(\"Metadata-Flavor\", \"Google\")\n .get()\n .build();\n\n Response response = ok.newCall(request).execute();\n\n // Convert json to prety json\n return gson.toJson(jp.parse(response.body().string()));\n }\n\n @Override\n public void init() {\n // Setup ThymeLeaf\n ServletContextTemplateResolver templateResolver =\n new ServletContextTemplateResolver(this.getServletContext());\n\n templateResolver.setPrefix(\"/WEB-INF/templates/\");\n templateResolver.setSuffix(\".html\");\n templateResolver.setCacheTTLMs(Long.valueOf(1200000L)); // TTL=20m\n\n // Cache is set to true by default. Set to false if you want templates to\n // be automatically updated when modified.\n templateResolver.setCacheable(true);\n\n templateEngine = new TemplateEngine();\n templateEngine.setTemplateResolver(templateResolver);\n }\n\n @Override\n public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {\n String defaultServiceAccount = \"\";\n WebContext ctx = new WebContext(req, resp, getServletContext(), req.getLocale());\n\n resp.setContentType(\"text/html\");\n\n String environment =\n (String) System.getProperties().get(\"com.google.appengine.runtime.environment\");\n ctx.setVariable(\"production\", environment);\n\n // The metadata server is only on a production system\n if (environment.equals(\"Production\")) {\n\n TreeMap\u003cString, String\u003e m = new TreeMap\u003c\u003e();\n\n for (String key : metaPath) {\n m.put(key, fetchMetadata(key));\n if (key.contains(\"default/email\")) {\n defaultServiceAccount = m.get(key);\n }\n }\n\n ctx.setVariable(\"Metadata\", m.descendingMap());\n\n m = new TreeMap\u003c\u003e();\n for (String key : metaServiceAcct) {\n // substitute a service account for {account}\n key = key.replace(\"{account}\", defaultServiceAccount);\n m.put(key, fetchMetadata(key));\n }\n ctx.setVariable(\"sam\", m.descendingMap());\n\n // Recursivly get all info about service accounts -- Note tokens are leftout by default.\n ctx.setVariable(\"rsa\",\n fetchJsonMetadata(\"/computeMetadata/v1/instance/service-accounts/?recursive=true\"));\n // Recursivly get all data on Metadata server.\n ctx.setVariable(\"ram\", fetchJsonMetadata(\"/?recursive=true\"));\n }\n\n templateEngine.process(\"index\", ctx, resp.getWriter());\n\n }\n }\n\nIn the sample code, notice the check to make sure the app is running in\nproduction. If the app is running locally, no metadata will be returned from\nthe requests.\n\nAlso, notice the use of the [Google Gson JSON](https://github.com/google/gson)\nserializer / deserializer, the [OkHttp](http://square.github.io/okhttp/) HTTP\nand HTTP2 client, and the [Thymeleaf](http://www.thymeleaf.org/) templating\nsystem. These are not required, but they are useful libraries for your own\nprojects.\n\nRunning locally\n---------------\n\nThe metadata server is available for deployed applications: running locally\non the development server is not supported. You can add an environment check to\nyour code to expect metadata results only if the app is running in production,\nas shown in the sample code provided above: \n\n String environment =\n (String) System.getProperties().get(\"com.google.appengine.runtime.environment\");\n ctx.setVariable(\"production\", environment);\n\n // The metadata server is only on a production system\n if (environment.equals(\"Production\")) {\n ... //show metadata results\n }"]]