Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
O DNS público do Google fornece duas APIs do DoH distintas nestes endpoints:
https://dns.google/dns-query – RFC 8484 (GET e POST)
https://dns.google/resolve? – API JSON (GET)
A página Visão geral dos transportes seguros tem exemplos de linha de comando curl para usar APIs, detalhes de TLS e outros recursos comuns a DNS sobre TLS (DoT) e DoH.
O DNS público do Google não é compatível com URLs http: não seguros para chamadas de API.
Métodos HTTP
GET
O uso do método GET pode reduzir a latência, já que ele é armazenado em cache com mais eficiência.
As solicitações GET RFC 8484 precisam ter um parâmetro de consulta ?dns= com uma mensagem DNS codificada em Base64Url.
O método GET é o único compatível com a API JSON.
POST
O método POST só é compatível com a API RFC 8484 e usa uma mensagem DNS
binária com o aplicativo Content-Type/dns-message no corpo da solicitação e
na resposta HTTP do DoH.
HEAD
No momento, HEAD não é compatível e retorna um erro 400 Bad Request.
Outros métodos retornam erros 501 Not Implemented.
Códigos de status HTTP
O DoH do DNS público do Google retorna os seguintes códigos de status HTTP:
Concluído
200 OK
A análise HTTP e a comunicação com o resolvedor de DNS foram bem-sucedidas, e o
conteúdo do corpo da resposta é uma resposta DNS em codificação binária ou JSON,
dependendo do endpoint de consulta, no cabeçalho Accept e nos parâmetros GET.
Redirecionamentos
301 Movido permanentemente
Os clientes precisam tentar novamente no URL fornecido no cabeçalho Location:. Se a consulta original for uma solicitação POST, os clientes só precisarão tentar novamente com GET se o novo URL especificar um argumento de parâmetro dns GET. Caso contrário, os clientes precisarão tentar novamente com POST.
Outros códigos, como 302 encontrado, redirecionamento temporário 307 ou redirecionamento permanente
308, podem ser usados no futuro, e os clientes do DoH precisam lidar com todos os quatro códigos.
As respostas com os códigos permanentes 301 e 308 precisam ser armazenadas em cache indefinidamente.
Se for prático, os usuários podem receber uma solicitação para atualizar a configuração original
usando o novo URL.
As solicitações POST que recebem respostas 307 ou 308 sempre devem ser repetidas com POST.
Erros
As respostas de erro terão uma explicação do status HTTP no corpo, usando HTML ou texto simples.
400 Solicitação inválida
Problemas ao analisar os parâmetros GET ou uma mensagem de solicitação DNS inválida.
Para parâmetros GET incorretos, o corpo do HTTP deve explicar o erro. A maioria das mensagens
DNS inválidas recebe um erro "200 OK" com um FORMERR. O erro HTTP é retornado para
mensagens ilegíveis sem seção de pergunta, uma sinalização QR indicando uma resposta ou
outras combinações de sinalizações sem sentido com erros de análise de DNS binário.
413 Payload muito grande
Um corpo de solicitação POST RFC 8484 excedeu o tamanho máximo da mensagem de 512 bytes.
URI 414 muito longo
O cabeçalho da consulta GET era muito grande ou o parâmetro dns tinha uma mensagem DNS codificada em Base64Url
que excedeva o tamanho máximo de mensagem de 512 bytes.
415 Tipo de mídia incompatível
O corpo POST não tinha um cabeçalho Content-Type application/dns-message.
429 número excessivo de solicitações
O cliente enviou muitas solicitações em um determinado período. Os clientes
precisam parar de enviar solicitações até o momento especificado no cabeçalho
"Tentar novamente depois"
(um tempo relativo em segundos).
500 Internal Server Error
Erros de DoH internos de DNS público do Google.
501 Não implementado
Somente os métodos GET e POST são implementados. Outros métodos recebem esse erro.
502 Bad Gateway
O serviço DoH não conseguiu entrar em contato com os resolvedores de DNS público do Google.
No caso de uma resposta 502, embora uma nova tentativa em um endereço DNS público
alternativo do Google possa ajudar, uma resposta substituta mais eficaz seria tentar
outro serviço DoH ou alternar para o DNS UDP ou TCP tradicional em 8.8.8.8.
Benefícios do DoH
O uso de HTTPS, e não apenas a criptografia TLS, tem alguns benefícios práticos:
As APIs HTTPS com ampla disponibilidade e suporte simplificam a implementação do
DNS público do Google e de clientes em potencial.
Um serviço HTTPS fornece aos apps da Web acesso a todos os tipos de registro DNS,
evitando as limitações das APIs DNS e do navegador atuais, que geralmente
oferecem suporte apenas para pesquisas de host para endereço.
Os clientes que implementam o suporte a HTTPS baseado em QUIC com UDP podem evitar problemas como
o bloqueio "head-of-line" que pode ocorrer ao usar o transporte TCP.
Práticas recomendadas de privacidade para DoH
Os desenvolvedores de aplicativos de DoH precisam considerar as práticas recomendadas de privacidade
descritas na RFC 8484 e
ampliadas abaixo:
Limitar o uso de cabeçalhos HTTP
Os cabeçalhos HTTP revelam informações sobre a implementação de DoH do cliente e podem ser usados para tornar os clientes anônimos. Cabeçalhos como Cookie, User-Agent e Accept-Language são os piores infratores, mas até mesmo o conjunto de cabeçalhos enviados pode ser revelador. Para minimizar esse risco, envie apenas os cabeçalhos HTTP necessários para DoH: Host, Content-Type (para POST) e, se necessário, Accept.
O user agent precisa ser incluído em qualquer versão de desenvolvimento ou teste.
Usar opções de padding do EDNS
Siga as orientações no RFC 8467 (link em inglês) para
usar as opções de preenchimento EDNS a fim de preencher consultas DoH em alguns tamanhos comuns para
proteger contra a análise de tráfego. O uso do padding HTTP/2 também é possível, mas,
ao contrário do preenchimento EDNS, não obterá padding nas respostas dos servidores DoH.
Use POST RFC 8484 somente para aplicativos ou modos de navegador que exigem privacidade
O uso de POST para consultas de DoH reduz a capacidade de cache das respostas e pode aumentar a latência do DNS. Portanto, em geral, ele não é recomendado. No entanto, reduzir
o armazenamento em cache é provavelmente desejável para aplicativos sensíveis à privacidade e pode
proteger contra ataques de tempo de apps da Web que tentam determinar quais
domínios o usuário visitou recentemente.
Issues
Para informar um bug ou solicitar um novo recurso, abra um problema no DoH.
[null,null,["Última atualização 2025-07-25 UTC."],[[["\u003cp\u003eGoogle Public DNS offers two DoH APIs: \u003ccode\u003edns.google/dns-query\u003c/code\u003e (RFC 8484, GET & POST) and \u003ccode\u003edns.google/resolve\u003c/code\u003e (JSON API, GET only).\u003c/p\u003e\n"],["\u003cp\u003eDoH supports both IPv4 and IPv6 using HTTPS for enhanced security and wider accessibility.\u003c/p\u003e\n"],["\u003cp\u003eFor privacy, minimize HTTP headers, utilize EDNS padding, and consider RFC 8484 POST for sensitive applications.\u003c/p\u003e\n"],["\u003cp\u003eGoogle Public DNS returns various HTTP status codes, including 200 OK for success (check DNS response code for errors) and error codes like 400, 413, 414, 415, 429, 500, 501, and 502.\u003c/p\u003e\n"],["\u003cp\u003eDoH benefits include wider API support, access to all DNS record types for web apps, and potential performance improvements with QUIC.\u003c/p\u003e\n"]]],["Google Public DNS offers two DoH APIs: one using RFC 8484 (supporting GET and POST) and a JSON API (GET only). GET requests use Base64Url-encoded DNS messages in the query parameters; POST requests use binary DNS messages. The service returns standard HTTP status codes, including 200 OK for success, and various error codes (400, 413, 414, 415, 429, 500, 501, 502), with 301, 307, and 308 for redirection. Privacy best practices include limiting HTTP headers, using EDNS padding, and employing POST for sensitive applications.\n"],null,["# DNS-over-HTTPS (DoH)\n\nGoogle Public DNS provides two distinct DoH APIs at these endpoints:\n\n- https://dns.google/dns-query -- [RFC 8484](https://tools.ietf.org/html/rfc8484) (GET and POST)\n- https://dns.google/resolve? -- [JSON API](/speed/public-dns/docs/doh/json) (GET)\n\n| **Note:** There is also a human-friendly web interface at \u003chttps://dns.google/\u003e. This web app displays JSON results in a browser but does not implement an API; do not confuse its https://dns.google/query? URLs with the two API URLs.\n\nThe [Secure Transports Overview](/speed/public-dns/docs/secure-transports#doh)\npage has `curl` command line examples for using both APIs as well as details of\nTLS and other features common to both DNS over TLS (DoT) and DoH.\n\nDoH is also supported for the IPv6-only\n[Google Public DNS64 service](/speed/public-dns/docs/dns64#secure).\n\nGoogle Public DNS does not support insecure `http:` URLs for API calls.\n\nHTTP methods\n------------\n\nGET\n: Using the GET method can reduce latency, as it is cached more effectively.\n RFC 8484 GET requests must have a `?dns=` query parameter with a\n Base64Url encoded DNS message.\n The GET method is the only method supported for the JSON API.\n\nPOST\n: The POST method is only supported for the RFC 8484 API and uses a binary DNS\n message with Content-Type application/dns-message in the request body and in\n the DoH HTTP response.\n\nHEAD\n: *HEAD is not currently supported, and returns a 400 Bad Request error*.\n\nOther methods return 501 Not Implemented errors.\n\nHTTP status codes\n-----------------\n\nGoogle Public DNS DoH returns the following HTTP status codes:\n\n### Success\n\n200 OK\n: HTTP parsing and communication with DNS resolver was successful, and the\n response body content is a DNS response in either binary or JSON encoding,\n depending on the query endpoint, Accept header and GET parameters.\n| **Note:** An HTTP success may still be a DNS failure. Check the DNS response code (JSON \"Status\" field) for the DNS errors SERVFAIL, FORMERR, REFUSED, and NOTIMP.\n\n### Redirections\n\n301 Moved Permanently\n: Clients should retry at the URL provided in the `Location:` header. If the\n original query was a POST request, clients should only retry with GET if the\n new URL specifies a `dns` GET parameter argument; otherwise clients should\n retry with POST.\n\nOther codes such as 302 Found, 307 Temporary Redirect or 308 Permanent Redirect\nmay be used in the future, and DoH clients should handle all four codes.\n\nResponses with the permanent 301 and 308 codes should be cached indefinitely,\nand if practical, users may be prompted to update their original configuration\nusing the new URL.\n\nPOST requests that get 307 or 308 responses should always be retried with POST.\n\n### Errors\n\nError responses will have an explanation of the HTTP status in the body,\nusing either HTML or plain text.\n\n400 Bad Request\n: Problems parsing the GET parameters, or an invalid DNS request message.\n For bad GET parameters, the HTTP body should explain the error. Most invalid\n DNS messages get a 200 OK with a FORMERR; the HTTP error is returned for\n garbled messages with no Question section, a QR flag indicating a reply, or\n other nonsensical flag combinations with binary DNS parse errors.\n\n413 Payload Too Large\n: An RFC 8484 POST request body exceeded the 512 byte maximum message size.\n\n414 URI Too Long\n: The GET query header was too large or the `dns` parameter had a Base64Url\n encoded DNS message exceeding the 512 byte maximum message size.\n\n415 Unsupported Media Type\n: The POST body did not have an `application/dns-message` Content-Type header.\n\n429 Too Many Requests\n: The client has sent too many requests in a given amount of time. Clients\n should stop sending requests until the time specified in the Retry-After\n header (a relative time in seconds).\n\n500 Internal Server Error\n: Google Public DNS internal DoH errors.\n\n501 Not Implemented\n: Only GET and POST methods are implemented, other methods get this error.\n\n502 Bad Gateway\n: The DoH service could not contact Google Public DNS resolvers.\n\nIn the case of a 502 response, although retrying on an alternate Google Public\nDNS address might help, a more effective fallback response would be to try\nanother DoH service, or to switch to traditional UDP or TCP DNS at 8.8.8.8.\n\nBenefits of DoH\n---------------\n\nUsing HTTPS, not just TLS encryption, has some practical benefits:\n\n- Widely available and well-supported HTTPS APIs simplify implementation for both Google Public DNS itself and potential clients.\n- An HTTPS service provides web apps with access to all DNS record types, avoiding the limitations of existing browser and OS DNS APIs, which generally support only host-to-address lookups.\n- Clients that implement QUIC UDP-based HTTPS support can avoid problems like head-of-line blocking that can occur when using TCP transport.\n\nPrivacy Best Practices for DoH\n------------------------------\n\nDevelopers of DoH applications should consider the privacy best practices\noutlined in [RFC 8484](https://tools.ietf.org/html/rfc8484#section-8) and\nexpanded below:\n\n- Limit use of HTTP Headers\n\n HTTP headers reveal information about the client's DoH implementation and\n can be used to deanonymize clients. Headers like Cookie, User-Agent, and\n Accept-Language are the worst offenders, but even the set of headers sent\n can be revealing. To minimize this risk, send only the HTTP headers required\n for DoH: Host, Content-Type (for POST), and if necessary, Accept.\n User-Agent should be included in any development or testing versions.\n- Use EDNS padding options\n\n Follow the guidance in [RFC 8467](https://tools.ietf.org/html/rfc8467) for\n use of EDNS padding options to pad DoH queries to a few common lengths to\n protect against traffic analysis. Use of HTTP/2 padding is also possible but\n unlike EDNS padding, will not elicit padding on responses from DoH servers.\n- Use RFC 8484 POST only for privacy sensitive applications or browser modes\n\n Using POST for DoH queries reduces the cacheability of responses and can\n increase DNS latency, so it is not generally recommended. However, reducing\n caching is probably desirable for privacy sensitive applications, and might\n protect against timing attacks from web apps trying to determine what\n domains the user has visited lately.\n\nIssues\n------\n\nTo report a bug or request a new feature, please open an [issue for DoH](https://issuetracker.google.com/issues/new?component=191657&template=1189745)."]]