G.9. utl_http — доступ к данным в Интернете по протоколу HTTP #
utl_http — это расширение Postgres Pro, которое позволяет получать доступ к данным в Интернете по протоколу HTTP (HTTP/1.0 и HTTP/1.1), выполняя HTTP-вызовы из SQL и PL/pgSQL. Функциональность, предоставляемая этим модулем, во многом пересекается с функциональностью пакета UTL_HTTP в Oracle. С помощью utl_http можно писать программы, взаимодействующие с HTTP-серверами. Кроме того, расширение utl_http содержит функции, которые можно использовать в запросах SQL, поддерживает протокол HTTP через SSL, также известный как HTTPS, и HTTP-методы GET, POST, PUT, UPLOAD, PATCH, HEAD, OPTIONS, DELETE, TRACE (см. https://datatracker.ietf.org/doc/html/rfc9110#name-methods), а также любые пользовательские HTTP-методы.
Расширение utl_http обычно используется следующим образом:
Запрос создаётся функцией
begin_request.Задаются параметры запроса, подробнее они описаны в Подразделе G.9.3.3.
Ответ обрабатывается функцией
get_response.Полученный ответ обрабатывается с использованием процедур из Подраздел G.9.3.5.
G.9.1. Установка #
Расширение utl_http поставляется вместе с Postgres Pro Enterprise в отдельном пакете pgpro-orautl-ent-16 (подробные инструкции по установке приведены в Главе 17). Чтобы включить utl_http, создайте расширение с помощью следующего запроса:
CREATE EXTENSION utl_http;
Для корректной работы utl_http с SSL необходима библиотека libcurl с поддержкой OpenSSL. Например, libcurl4-openssl-dev для Ubuntu.
G.9.2. Типы данных #
Расширение utl_http предоставляет несколько типов данных:
Тип
reqпредставляет собой HTTP-запрос.CREATE TYPE req AS ( url varchar(32767), method varchar(64), http_version varchar(64) );
Таблица G.101. Параметры
reqПараметр Описание urlURL-адрес HTTP-запроса. Задаётся после создания запроса функцией begin_request.methodМетод, который будет применяться для ресурса, определяемого URL-адресом. Он задаётся после создания запроса функцией begin_requesthttp_versionВерсия HTTP-протокола, используемая для отправки запроса. Она задаётся после создания запроса функцией begin_request.Тип
respпредставляет собой HTTP-ответ.CREATE TYPE resp AS ( status_code integer, reason_phrase varchar(256), http_version varchar(64) );
Таблица G.102. Параметры
respПараметр Описание status_codeКод состояния, возвращаемый веб-сервером. Это трёхзначное целое число, показывающее результаты HTTP-запроса, обработанного веб-сервером. Этот код задаётся после обработки ответа функцией get_response.reason_phraseКороткое текстовое сообщение, возвращаемое веб-сервером и описывающее код состояния. Оно содержит краткое описание результатов HTTP-запроса, обработанного веб-сервером, и задаётся после обработки ответа функцией get_response.http_versionВерсия HTTP-протокола, используемая в HTTP-ответе. Она задаётся после обработки ответа функцией get_response.Тип
cookieпредставляет собой данные cookie HTTP. Типcookie_table— это набор cookie данных HTTP. По сути, это тип данных массива, создаваемого на основе автоматически созданного массива.CREATE TYPE cookie AS ( name varchar(256), value varchar(1024), domain varchar(256), expire timestamp with time zone, path varchar(1024), secure bool, version int, comment varchar(1024) ); CREATE DOMAIN cookie_table AS _cookie;
Таблица G.103. Поля типов
cookieиcookie_tableПараметр Описание nameИмя cookie HTTP. valueЗначение cookie. domainДомен, для которого действительны cookie. expireВремя истечения срока действия cookie. pathПодмножество URL-адресов, к которым относятся cookie. secureДолжны ли cookie возвращаться на веб-сервер только с использованием защищённых средств. versionВерсия спецификации cookie, которой соответствуют cookie. commentКомментарий, описывающий предполагаемое использование cookie. Тип
request_context_keyиспользуется для определения ключа контекста запроса. В Postgres Pro он представлен типомintegerи сохраняется из соображений совместимости для миграции из Oracle.
G.9.3. Функции и процедуры utl_http #
Обратите внимание, что параметр request_context в функциях и процедурах ниже сохраняется для совместимости при миграции из Oracle и не влияет на результат.
G.9.3.1. Простые HTTP-запросы #
Функции request_function и request_pieces_function берут URL-адрес в виде строки, подключаются к указанному в ней сайту и возвращают данные (обычно HTML), полученные с этого сайта.
-
request(#urltext,proxytextdefault null) returnstext Получает веб-страницу и возвращает не более первых 2000 байт этой страницы.
-
request_pieces(#urltext,max_piecesintdefault 32767,proxytextdefault null) returnstext Эта функция возвращает таблицу PL/pgSQL, состоящую из фрагментов данных по 2000 байт, полученных по заданному URL-адресу. Элементы таблицы, возвращаемые
request_pieces, представляют собой последовательные фрагменты данных, полученные в результате HTTP-запроса к этому URL-адресу.
G.9.3.2. Параметры сеанса #
Расширение utl_http предоставляет функции и процедуры для работы с конфигурацией и поведением по умолчанию при выполнении HTTP-запросов в сеансе пользователя базы данных. Когда запрос создаётся, он наследует параметры по умолчанию в отношении поддержки cookie, перенаправления, набора символов тела сообщения и тайм-аута передачи текущего сеанса. Когда создаётся ответ на запрос, он наследует эти параметры из запроса.
-
set_response_error_check(#enablebooldefault false) Эта процедура определяет, будет ли функция
get_responseвыдавать исключение, когда веб-сервер возвращает код состояния, указывающий на ошибку — код состояния в диапазоне 4xx или 5xx.-
get_response_error_check(#enablebool) Эта процедура проверяет, установлена ли проверка ошибок ответа.
-
set_transfer_timeout(#timeoutint4default 60) Эта процедура устанавливает значение тайм-аута по умолчанию для всех будущих HTTP-запросов, который должен соблюдаться расширением utl_http перед чтением HTTP-ответа с веб-сервера или прокси-сервера. Это значение тайм-аута можно использовать, чтобы избежать блокировки программ при загрузке веб-серверов или интенсивном сетевом трафике во время получения получении веб-страниц с веб-серверов. Значение тайм-аута по умолчанию — 60 секунд.
-
get_transfer_timeout(#timeoutint4) Эта процедура получает значение тайм-аута по умолчанию для всех будущих HTTP-запросов.
-
set_detailed_excp_support(#enablebooldefault false) Эта процедура определяет, выдаёт ли расширение utl_http подробное исключение. По умолчанию она выдаёт исключение
REQUEST_FAILEDпри сбое HTTP-запроса. Используйтеget_detailed_sqlcodeиget_detailed_sqlerrmдля получения более подробной информации об ошибке.Доступные исключения перечислены в Таблице G.104.
Таблица G.104. Исключения utl_http
Исключение Код ошибки Причина Где выдаётся исключение BAD_ARGUMENT29265 Передан некорректный аргумент Любой интерфейс HTTP-запроса или ответа, если включена выдача подробных исключений HEADER_NOT_FOUND29261 Заголовок не найден get_header,get_header_by_name, когда включена выдача подробных исключенийEND_OF_BODY29266 Достигнут конец тела HTTP-ответа read_raw,read_textиread_line, когда включена выдача подробных исключенийHTTP_CLIENT_ERROR29268 Код состояния ответа из get_responseуказывает на то, что произошла ошибка клиента (код состояния в диапазоне 4xx). Из функцииbegin_requestHTTP-прокси возвращает код состояния в диапазоне 4xx при выполнении HTTPS-запроса через прокси.get_response,begin_request, когда включена выдача подробных исключенийHTTP_SERVER_ERROR29269 Код состояния ответа из get_responseуказывает на то, что произошла ошибка сервера (код состояния в диапазоне 5xx). Из функцииbegin_requestHTTP-прокси возвращает код состояния в диапазоне 5xx при выполнении HTTPS-запроса через прокси.get_response,begin_request, когда включена выдача подробных исключенийREQUEST_FAILED29273 Ошибка выполнения запроса Любой интерфейс HTTP-запроса или ответа, если отключена выдача подробных исключений -
get_detailed_excp_support(#enablebool) Эта процедура проверяет, выдаст ли utl_http подробное исключение или нет.
G.9.3.3. HTTP-запросы #
Расширение utl_http предоставляет функции и процедуры для запуска HTTP-запроса, работы с атрибутами и отправки информации запроса на веб-сервер. Когда запрос создаётся, он наследует параметры по умолчанию в отношении поддержки cookie, перенаправления, набора символов тела сообщения и тайм-аута передачи текущего сеанса. Параметры можно изменить, вызвав интерфейс запроса.
-
begin_request(#urltext,methodtextdefault 'GET',http_versiontextdefault null,request_contextrequest_context_keydefault null) returnsreq Эта функция начинает новый HTTP-запрос.
-
set_header(#rreq,nametext,valuetext) Эта процедура устанавливает заголовок HTTP-запроса для будущего запроса.
-
set_authentication(#rreq,usernametext,passwordtext,schemetextdefault 'Basic',for_proxybooleandefault false) Эта процедура устанавливает информацию о HTTP-аутентификации в заголовке HTTP-запроса. Веб-серверу эта информация нужна для авторизации запроса.
-
set_body_charset(#rreq,charsetnamedefault null) Эта процедура устанавливает набор символов, когда тип носителя —
text, но набор символов не указан в заголовкеContent-Typeи может принимать одну из следующих форм:Устанавливает набор символов по умолчанию для тела всех будущих HTTP-запросов.
set_body_charset( charset IN name DEFAULT NULL)
Устанавливает набор символов тела запроса.
set_body_charset( r INOUT req, charset IN name DEFAULT NULL)
-
set_cookie_support(#rreq,enablebool) Эта процедура определяет поддержку cookie и может принимать одну из следующих форм:
Включает или отключает поддержку cookie HTTP в запросе.
set_cookie_support( r INOUT req, enable IN bool DEFAULT true)
Устанавливает, будут ли будущие HTTP-запросы поддерживать cookie HTTP, а также максимальное количество cookie, поддерживаемых в текущем сеансе пользователя базы данных.
set_cookie_support( enable IN bool, max_cookies IN int4 DEFAULT 300, max_cookies_per_site IN int4 DEFAULT 20)
-
set_follow_redirect(#rreq,max_redirectsint4default 3) Эта процедура устанавливает максимальное количество раз, когда utl_http должен следовать инструкции HTTP-перенаправления в HTTP-ответах на запросы в
get_response. По умолчанию — 3.-
set_proxy(#proxytext,no_proxy_domainstext) Эта процедура устанавливает прокси-сервер, который будет использоваться для HTTP-запросов или других протоколов. Обратите внимание, что прокси-сервер не будет работать без корректного сертификата.
-
write_raw(#rreq,databytea) Эта процедура записывает двоичные данные в тело HTTP-запроса для будущего запроса.
-
write_text(#rreq,datatext) Эта процедура записывает текстовые данные в тело HTTP-запроса для будущего запроса.
-
end_request(#rreq) Эта процедура завершает HTTP-запрос путём сброса параметров запроса.
G.9.3.4. Параметры и запросы #
-
set_option(#texttext) Задать параметры для всех будущих запросов в сеансе.
PROCEDURE set_option( option IN text, value IN text );-
set_option(#rreqtexttext) Задать параметр для указанного запроса.
PROCEDURE set_option( r IN req, option IN text, value IN text );-
get_option(#text) Показать значение по умолчанию, установленное для всех будущих запросов в этом сеансе.
FUNCTION get_option( option IN text ) RETURNS text;-
get_option(#rreqtext) Показать значение параметра по умолчанию, установленное для существующего запроса.
FUNCTION get_option( r IN req, option IN text )
У данных функций есть следующие параметры:
OPT_SSL_VERIFYPEERпроверяет SSL-сертификат удалённой стороны. Этот параметр можно задать для запроса или в качестве значения по умолчанию для всех будущих запросов. Возможные значения:0или1(по умолчанию).OPT_SSL_VERIFYHOSTсверяет имя сертификата с именем компьютера. Этот параметр можно задать для конкретного запроса или в качестве значения по умолчанию для всех будущих запросов.Этот параметр доступен только для версии
libcurl7.8.1 и выше. Возможные значения:0,1или2(значение по умолчанию). Когда для параметра задано значение0, соединение устанавливается независимо от соответствия имён в сертификате. Используйте это значение с осторожностью.Также не рекомендуется использовать значение
1, поскольку это может привести к неожиданным результатам в зависимости от версииlibcurl. За дополнительной информацией обратитесь к официальной документацииlibcurl.
G.9.3.5. HTTP-ответы #
Расширение utl_http предоставляет функции и процедуры для управления HTTP-ответом, полученным из get_response, и получения информации об ответе от веб-сервера. Когда создаётся ответ на запрос, он наследует параметры поддержки cookie, перенаправления, набора символов тела сообщения и тайм-аута передачи из запроса. Вызвав интерфейс ответа, можно изменить только набор символов тела.
-
end_response(#rresp) Эта процедура завершает HTTP-ответ путём сброса параметров запроса.
-
get_authentication(#rresp,schemetext,realmtext,for_proxybooldefault false) Эта процедура получает информацию о HTTP-аутентификации, необходимую для принятия запроса веб-сервером, как указано в заголовке HTTP-ответа.
-
get_header(#rresp,nint4,nametext,valuetext) Эта процедура возвращает n-е имя заголовка HTTP-ответа и значение, возвращаемое в ответе.
-
get_header_by_name(#rresp,nametext,valuetext,nint4default 1) Эта процедура возвращает значение заголовка HTTP-ответа, возвращаемое в ответе, по заданному имени заголовка.
-
get_header_count(#rresp) returnsint4 Эта функция возвращает количество заголовков HTTP-ответа, возвращаемых в ответе.
-
get_response(#rreq,return_info_responsebooldefault false) returnsresp Эта функция завершает HTTP-запрос и ответ: читает HTTP-ответ и обрабатывает строку состояния и заголовки ответа. Код состояния, описание причины и версия HTTP-протокола сохраняются в записи ответа.
-
read_raw(#rresp,databytea,lenint4default null) Эта процедура считывает тело HTTP-ответа в двоичной форме и возвращает выходные данные в буфер со стороны вызывающего.
-
read_line(#rresp,datatext,remove_crlfbooldefault false) Эта процедура считывает тело HTTP-ответа в текстовой форме до конца строки, и возвращает выходные данные в буфер со стороны вызывающего.
-
read_text(#rresp,datatext,lenint4default null) Эта процедура считывает тело HTTP-ответа в текстовой форме и возвращает выходные данные в буфер со стороны вызывающего.
G.9.3.6. Данные cookie HTTP #
Расширение utl_http предоставляет функции и процедуры для управления cookie.
-
add_cookies(#cookiescookie_table,request_contextrequest_context_keydefault null) Эта процедура добавляет cookie, поддерживаемые расширением utl_http.
-
clear_cookies(#request_contextrequest_context_keydefault null) Эта процедура удаляет все cookie с которые в настоящее время работает расширение utl_http.
-
get_cookie_count(#request_contextrequest_context_keydefault null) returnsint4 Эта функция возвращает объём cookie, с которым и в настоящее время работает расширение utl_http для всех веб-серверов.
-
get_cookies(#cookiescookie_table,request_contextrequest_context_keydefault null) returnscookie_table Эта функция возвращает полный объём cookie, с которым в настоящее время работает расширение utl_http для всех веб-серверов.
G.9.3.7. Условия возникновения ошибок #
Расширение utl_http предоставляет функции для получения информации об ошибках.
-
get_detailed_sqlcode() returns#int4 Получает код
SQLCODEс описанием последнего выданного исключения (см. Таблицу G.104).-
get_detailed_sqlerrm() returns#text Получает код
SQLERRMс описанием последнего выданного исключения (см. Таблицу G.104).
G.9.4. Пример #
DO $$
DECLARE
request utl_http.req;
response utl_http.resp;
text_body text;
BEGIN
CALL utl_http.set_body_charset('WIN1251');
request := utl_http.begin_request('https://postgrespro.ru/', 'GET');
CALL utl_http.set_authentication(request, 'admin', 'qwerty', 'Basic', FALSE);
response := utl_http.get_response(request);
CALL utl_http.read_text(response, text_body);
text_body = substring(text_body FROM 720 FOR 245);
RAISE NOTICE '%', text_body;
END$$;Схему utl_http можно явно задать в параметре search_path и опускать в теле запроса:
SET search_path =utl_http, public;
Тогда пример выше будет выглядеть так:
DO $$
DECLARE
request req;
response resp;
text_body text;
BEGIN
CALL set_body_charset('WIN1251');
request := begin_request('https://postgrespro.ru/docs/enterprise/17/utl-http', 'GET');
CALL set_authentication(request, 'admin', 'qwerty', 'Basic', FALSE);
response := get_response(request);
CALL read_text(response, text_body);
text_body = substring(text_body FROM 720 FOR 245);
RAISE NOTICE '%', text_body;
END$$;Пример самоподписанного сертификата:
test=# SELECT * FROM utl_http.request('https://localhost:5001');
ERROR: utl_http failed while handling the request to "https://localhost:5001".
Details: "SSL peer certificate or SSH remote key was not OK"
test=# call utl_http.set_option('OPT_SSL_VERIFYPEER', '0');
test=# call utl_http.set_option('OPT_SSL_VERIFYHOST', '0');
test=# SELECT * FROM substr(utl_http.request('https://localhost:5001'), 0, 50);
substr
------------------
<!DOCTYPE html> +
<html lang="en">+
+
<head> +
<met
(1 row)Пример клиентской аутентификации по ключу:
SELECT * FROM utl_http.begin_request('https://some_server');
CALL utl_http.set_option((NULL, NULL, NULL), 'OPT_CAINFO_BLOB', '-----BEGIN CERTIFICATE-----
...
Y7707nS0spc1qVPMSQ==
-----END CERTIFICATE-----
');
CALL utl_http.set_option((NULL, NULL, NULL), 'OPT_SSLCERT_BLOB', '-----BEGIN CERTIFICATE-----
...
GMNTQVzSHmuu8tw5W4GjNUQL2Wx5h/yuMD5dS+vCeQ==
-----END CERTIFICATE-----
');
CALL utl_http.set_option((NULL, NULL, NULL), 'OPT_SSLKEY_BLOB', '-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-256-CBC,2557386B35596227304F2F017F07B467
...
-----END RSA PRIVATE KEY-----
');
CALL utl_http.set_option((NULL, NULL, NULL), 'OPT_KEYPASSWD', 'superpassword');
SELECT * FROM utl_http.get_response((NULL, NULL, NULL));G.9. utl_http — access data on the Internet over the HTTP protocol #
utl_http is a Postgres Pro extension that allows accessing data on the Internet over the HTTP protocol (HTTP/1.0 and HTTP/1.1) by invoking HTTP callouts from SQL and PL/pgSQL. The functionality provided by this module overlaps substantially with the functionality of Oracle's UTL_HTTP package. With utl_http, you can write programs that communicate with HTTP servers. utl_http also contains functions that can be used in SQL queries. The extension supports HTTP over SSL, also known as HTTPS. The supported methods are GET, POST PUT, UPLOAD, PATCH, HEAD, OPTIONS, DELETE, TRACE (see https://datatracker.ietf.org/doc/html/rfc9110#name-methods), as well as any custom HTTP-methods.
utl_http is typically used as follows:
A request is created by
begin_request.Request parameters are set, for more information see Section G.9.3.3.
The response is processed by
get_response.The obtained response is manipulated using procedures from Section G.9.3.5.
G.9.1. Installation #
The utl_http extension is provided with Postgres Pro Enterprise in a separate pre-built package pgpro-orautl-ent-16 (for the detailed installation instructions, see Chapter 17). To enable utl_http, create the extension using the following query:
CREATE EXTENSION utl_http;
For utl_http to work with SSL, a libcurl library with OpenSSL support is required. E.g., libcurl4-openssl-dev for Ubuntu.
G.9.2. Data Types #
The utl_http extension provides several data types:
reqrepresents an HTTP request.CREATE TYPE req AS ( url varchar(32767), method varchar(64), http_version varchar(64) );
Table G.101.
reqParametersParameter Description urlThe URL of the HTTP request. It is set after the request is created by begin_request.methodThe method to be performed on the resource identified by the URL. It is set after the request is created by begin_requesthttp_versionThe HTTP protocol version used to send the request. It is set after the request is created by begin_request.resprepresents an HTTP response.CREATE TYPE resp AS ( status_code integer, reason_phrase varchar(256), http_version varchar(64) );
Table G.102.
respParametersParameter Description status_codeThe status code returned by the web server. It is a 3-digit integer that indicates the results of the HTTP request as handled by the web server. It is set after the response is processed by get_response.reason_phraseThe short textual message returned by the web server that describes the status code. It gives a brief description of the results of the HTTP request as handled by the web server. It is set after the response is processed by get_response.http_versionThe HTTP protocol version used in the HTTP response. It is set after the response is processed by get_response.The
cookietype represents an HTTP cookie. Thecookie_tabletype represents a collection of HTTP cookies. It is essentially an array data type created on the basis of the array created automatically.CREATE TYPE cookie AS ( name varchar(256), value varchar(1024), domain varchar(256), expire timestamp with time zone, path varchar(1024), secure bool, version int, comment varchar(1024) ); CREATE DOMAIN cookie_table AS _cookie;
Table G.103. Fields of
cookieandcookie_tableParameter Description nameThe name of the HTTP cookie. valueThe value of the cookie. domainThe domain for which the cookie is valid. expireThe time by which the cookie will expire. pathThe subset of URLs to which the cookie applies. secureShould the cookie be returned to the web server using secured means only. versionThe version of the HTTP cookie specification the cookie conforms. commentThe comment that describes the intended use of the cookie. The
request_context_keytype is used to define the key to a request context. In Postgres Pro, it is represented byintegerand preserved for the reasons of compatibility when migrating from Oracle.
G.9.3. utl_http Functions and Procedures #
Note that the request_context in functions and procedures below is preserved for the reasons of compatibility when migrating from Oracle, and does not affect the result.
G.9.3.1. Simple HTTP Fetches #
request_function and request_pieces_function take a string URL, contact that site, and return the data (typically HTML) obtained from that site.
-
request(#urltext,proxytextdefault null) returnstext Fetches a web page. This function returns the first 2000 bytes of the page at most.
-
request_pieces(#urltext,max_piecesintdefault 32767,proxytextdefault null) returnstext This function returns a PL/pgSQL table of 2000-byte pieces of the data retrieved from the given URL. The elements of the table returned by
request_piecesare successive pieces of the data obtained from the HTTP request to that URL.
G.9.3.2. Session Settings #
utl_http provides functions and procedures to manipulate the configuration and default behavior when HTTP requests are executed within a database user session. When a request is created, it inherits the default settings of the HTTP cookie support, follow-redirect, body character set, and transfer timeout of the current session. When a response is created for a request, it inherits those settings from the request.
-
set_response_error_check(#enablebooldefault false) This procedure sets whether or not
get_responseraises an exception when the web server returns a status code that indicates an error — a status code in the 4xx or 5xx range.-
get_response_error_check(#enablebool) This procedure checks if the response error check is set or not.
-
set_transfer_timeout(#timeoutint4default 60) This procedure sets the default timeout value for all future HTTP requests that utl_http should attempt while reading the HTTP response from the web server or proxy server. This timeout value may be used to avoid the programs from being blocked by busy web servers or heavy network traffic while retrieving web pages from the web servers. The default value of the timeout is 60 seconds.
-
get_transfer_timeout(#timeoutint4) This procedure retrieves the default timeout value for all future HTTP requests.
-
set_detailed_excp_support(#enablebooldefault false) This procedure sets whether utl_http raises a detailed exception. By default, it raises the
REQUEST_FAILEDexception when an HTTP request fails. Useget_detailed_sqlcodeandget_detailed_sqlerrmfor more detailed information about the error.The available exceptions are listed in Table G.104.
Table G.104. utl_http Exceptions
Exception Error Code Reason Where Raised BAD_ARGUMENT29265 The argument passed to the interface is bad Any HTTP request or response interface when detailed exception is enabled HEADER_NOT_FOUND29261 The header is not found get_header,get_header_by_namewhen detailed exception is enabledEND_OF_BODY29266 The end of HTTP response body is reached read_raw,read_text, andread_linewhen detailed exception is enabledHTTP_CLIENT_ERROR29268 From get_responsethe response status code indicates that a client error has occurred (status code in 4xx range). Frombegin_requestthe HTTP proxy returns a status code in the 4xx range when making an HTTPS request through the proxy.get_response,begin_requestwhen detailed exception is enabledHTTP_SERVER_ERROR29269 From get_responsethe response status code indicates that a server error has occurred (status code in 5xx range). Frombegin_requestthe HTTP proxy returns a status code in the 5xx range when making an HTTPS request through the proxy.get_response,begin_requestwhen detailed exception is enabledREQUEST_FAILED29273 The request fails to execute Any HTTP request or response interface when detailed exception is disabled -
get_detailed_excp_support(#enablebool) This procedure checks if utl_http will raise a detailed exception or not.
G.9.3.3. HTTP Requests #
utl_http provides functions and procedures to begin an HTTP request, manipulate attributes, and send the request information to the web server. When a request is created, it inherits the default settings of the HTTP cookie support, follow-redirect, body character set, and transfer timeout of the current session. The settings can be changed by calling the request interface.
-
begin_request(#urltext,methodtextdefault 'GET',http_versiontextdefault null,request_contextrequest_context_keydefault null) returnsreq This function begins a new HTTP request.
-
set_header(#rreq,nametext,valuetext) This procedure sets the HTTP request header for the future request.
-
set_authentication(#rreq,usernametext,passwordtext,schemetextdefault 'Basic',for_proxybooleandefault false) This procedure sets HTTP authentication information in the HTTP request header. The web server needs this information to authorize the request.
-
set_body_charset(#rreq,charsetnamedefault null) This procedure sets the character set when the media type is
textbut the character set is not specified in theContent-Typeheader and may take one of the following forms:Sets the default character set of the body of all future HTTP requests.
set_body_charset( charset IN name DEFAULT NULL)
Sets the character set of the request body.
set_body_charset( r INOUT req, charset IN name DEFAULT NULL)
-
set_cookie_support(#rreq,enablebool) This procedure determines cookie support and may take one of the following forms:
Enables or disables support for the HTTP cookies in the request.
set_cookie_support( r INOUT req, enable IN bool DEFAULT true)
Sets whether future HTTP requests will support HTTP cookies, and the maximum number of cookies maintained in the current database user session.
set_cookie_support( enable IN bool, max_cookies IN int4 DEFAULT 300, max_cookies_per_site IN int4 DEFAULT 20)
-
set_follow_redirect(#rreq,max_redirectsint4default 3) This procedure sets the maximum number of times utl_http should follow HTTP redirect instruction in the HTTP responses to requests in
get_response. Default is 3.-
set_proxy(#proxytext,no_proxy_domainstext) This procedure sets the proxy to be used for requests of HTTP or other protocols. Note that proxy with no valid certificate will not work properly.
-
write_raw(#rreq,databytea) This procedure writes binary data in the HTTP request body for the future request.
-
write_text(#rreq,datatext) This procedure writes text data in the HTTP request body for the future request.
-
end_request(#rreq) This procedure ends the HTTP request by resetting request parameters.
G.9.3.4. Options and Requests #
-
set_option(#texttext) Set options for all future requests in this session.
PROCEDURE set_option( option IN text, value IN text );-
set_option(#rreqtexttext) Set option for the specified request.
PROCEDURE set_option( r IN req, option IN text, value IN text );-
get_option(#text) Show the default value set for all future requests in this session.
FUNCTION get_option( option IN text ) RETURNS text;-
get_option(#rreqtext) Show the default option value set for an existing request.
FUNCTION get_option( r IN req, option IN text )
These functions have the following options:
OPT_SSL_VERIFYPEER— verify the peer's SSL certificate. It can be specified for a request or as a defult value for future requests. Possible values are0or1(default).OPT_SSL_VERIFYHOST— verify the certificate's name against host. It can be specified for a request or as a defult value for future requests.This option is available only for
libcurlversion 7.8.1 or later. Possible values are0,1, or2(default). When the option is set to0, the connection succeeds regardless of the names in the certificate. Use this value with caution.It is also not recommended to use the
1value, as it may lead to unexpected results depending on thelibcurlversion. For more information, see thelibcurlofficial documentation.
G.9.3.5. HTTP Responses #
utl_http provides functions and procedures to manipulate an HTTP response obtained from get_response and receive response information from the web server. When a response is created for a request, it inherits settings of the HTTP cookie support, follow-redirect, body character set, and transfer timeout from the request. Only the body character set can be changed by calling the response interface.
-
end_response(#rresp) This procedure ends the HTTP response by resetting request parameters.
-
get_authentication(#rresp,schemetext,realmtext,for_proxybooldefault false) This procedure retrieves the HTTP authentication information needed for the request to be accepted by the web server as indicated in the HTTP response header.
-
get_header(#rresp,nint4,nametext,valuetext) This procedure returns the n-th HTTP response header name and value returned in the response.
-
get_header_by_name(#rresp,nametext,valuetext,nint4default 1) This procedure returns the HTTP response header value returned in the response given the name of the header.
-
get_header_count(#rresp) returnsint4 This function returns the number of HTTP response headers returned in the response.
-
get_response(#rreq,return_info_responsebooldefault false) returnsresp This function completes the HTTP request and response: reads the HTTP response and processes the status line and response headers. The status code, reason phrase and the HTTP protocol version are stored in the response record.
-
read_raw(#rresp,databytea,lenint4default null) This procedure reads the HTTP response body in binary form and returns the output in the caller-supplied buffer.
-
read_line(#rresp,datatext,remove_crlfbooldefault false) This procedure reads the HTTP response body in text form until the end of line is reached and returns the output in the caller-supplied buffer.
-
read_text(#rresp,datatext,lenint4default null) This procedure reads the HTTP response body in text form and returns the output in the caller-supplied buffer.
G.9.3.6. HTTP Cookies #
utl_http provides functions and procedures to manipulate HTTP cookies.
-
add_cookies(#cookiescookie_table,request_contextrequest_context_keydefault null) This procedure adds the cookies maintained by utl_http.
-
clear_cookies(#request_contextrequest_context_keydefault null) This procedure clears all the cookies currently maintained by utl_http.
-
get_cookie_count(#request_contextrequest_context_keydefault null) returnsint4 This function returns the number of cookies currently maintained by utl_http set by all web servers.
-
get_cookies(#cookiescookie_table,request_contextrequest_context_keydefault null) returnscookie_table This function returns all the number of cookies currently maintained by utl_http set by all web servers.
G.9.3.7. Error Conditions #
utl_http provides functions to retrieve error information.
-
get_detailed_sqlcode() returns#int4 Retrieves the detailed
SQLCODEof the last exception raised (see Table G.104).-
get_detailed_sqlerrm() returns#text Retrieves the detailed
SQLERRMof the last exception raised (see Table G.104).
G.9.4. Example #
DO $$
DECLARE
request utl_http.req;
response utl_http.resp;
text_body text;
BEGIN
CALL utl_http.set_body_charset('WIN1251');
request := utl_http.begin_request('https://postgrespro.ru/', 'GET');
CALL utl_http.set_authentication(request, 'admin', 'qwerty', 'Basic', FALSE);
response := utl_http.get_response(request);
CALL utl_http.read_text(response, text_body);
text_body = substring(text_body FROM 720 FOR 245);
RAISE NOTICE '%', text_body;
END$$;
You can specify the utl_http schema in the search_path parameter explicitly to omit it in the body of a request:
SET search_path =utl_http, public;
The example above will then look as follows:
DO $$
DECLARE
request req;
response resp;
text_body text;
BEGIN
CALL set_body_charset('WIN1251');
request := begin_request('https://postgrespro.ru/docs/enterprise/17/utl-http', 'GET');
CALL set_authentication(request, 'admin', 'qwerty', 'Basic', FALSE);
response := get_response(request);
CALL read_text(response, text_body);
text_body = substring(text_body FROM 720 FOR 245);
RAISE NOTICE '%', text_body;
END$$;
Example for a self-signed certificate:
test=# SELECT * FROM utl_http.request('https://localhost:5001');
ERROR: utl_http failed while handling the request to "https://localhost:5001".
Details: "SSL peer certificate or SSH remote key was not OK"
test=# call utl_http.set_option('OPT_SSL_VERIFYPEER', '0');
test=# call utl_http.set_option('OPT_SSL_VERIFYHOST', '0');
test=# SELECT * FROM substr(utl_http.request('https://localhost:5001'), 0, 50);
substr
------------------
<!DOCTYPE html> +
<html lang="en">+
+
<head> +
<met
(1 row)
Example of client authentication with key:
SELECT * FROM utl_http.begin_request('https://some_server');
CALL utl_http.set_option((NULL, NULL, NULL), 'OPT_CAINFO_BLOB', '-----BEGIN CERTIFICATE-----
...
Y7707nS0spc1qVPMSQ==
-----END CERTIFICATE-----
');
CALL utl_http.set_option((NULL, NULL, NULL), 'OPT_SSLCERT_BLOB', '-----BEGIN CERTIFICATE-----
...
GMNTQVzSHmuu8tw5W4GjNUQL2Wx5h/yuMD5dS+vCeQ==
-----END CERTIFICATE-----
');
CALL utl_http.set_option((NULL, NULL, NULL), 'OPT_SSLKEY_BLOB', '-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-256-CBC,2557386B35596227304F2F017F07B467
...
-----END RSA PRIVATE KEY-----
');
CALL utl_http.set_option((NULL, NULL, NULL), 'OPT_KEYPASSWD', 'superpassword');
SELECT * FROM utl_http.get_response((NULL, NULL, NULL));