- HTTP-запрос методом GET.
- HttpClient
- Overview of HttpClient and the Windows.Web.Http namespace
- Send a simple GET request over HTTP
- POST binary data over HTTP
- POST JSON data over HTTP
- Exceptions in Windows.Web.Http
- HttpClient HttpClient
- Обзор HttpClient и пространства имен Windows.Web.Http Overview of HttpClient and the Windows.Web.Http namespace
- Отправка простого запроса GET через HTTP Send a simple GET request over HTTP
- Использование запроса POST для отправки двоичных данных по HTTP POST binary data over HTTP
- Передача данных JSON с помощью запроса POST по HTTP POST JSON data over HTTP
- Исключения в Windows.Web.Http Exceptions in Windows.Web.Http
HTTP-запрос методом GET.
Одним из способов, как можно отправить запрос по протоколу HTTP к серверу, является запрос методом GET. Этот метод является самым распространенным и запросы к серверу чаще всего происходят с его использованием.
Самый простой способ, как можно создать запрос методом GET- это набрать URL-адрес в адресную строку браузера.
Если у вас есть желание погрузиться в тему серверного программирования глубже, все мои уроки здесь.
Браузер передаст серверу примерно следующую информацию:
Запрос состоит из двух частей:
1. строка запроса (Request Line)
2. заголовки (Message Headers)
Обратите внимание, что GET запрос не имеет тела сообщения. Но, это не означает, что с его помощью мы не можем передать серверу никакую информацию. Это можно делать с помощью специальных GET параметров.
Чтобы добавить GET параметры к запросу, нужно в конце URL-адреса поставить знак «?» и после него начинать задавать их по следующему правилу:
К примеру, если мы хотим передать серверу два значения, имя пользователя и его возраст, то это можно сделать следующей строкой:
Когда выполнен данный запрос, данные попадают в так называемую переменную окружения QUERY_STRING, из которой их можно получить на сервере с помощью серверного языка веб-программирования.
Вот пример, как это можно сделать на языке PHP.
Конструкция $_GET[«имя_параметра»] позволяет выводить значение переданного параметра.
В результате выполнения этого кода в браузере выведется:
Кстати, переходя по какой-либо ссылке, которая оформлена в HTML вот так:
мы тоже выполняем запрос к серверу методом GET.
Все мои уроки по серверному программированию здесь.
Чтобы оставить сообщение, зарегистрируйтесь/войдите на сайт через:
Или зарегистрируйтесь через социальные сети:
HttpClient
Important APIs
Use HttpClient and the rest of the Windows.Web.Http namespace API to send and receive information using the HTTP 2.0 and HTTP 1.1 protocols.
Overview of HttpClient and the Windows.Web.Http namespace
The classes in the Windows.Web.Http namespace and the related Windows.Web.Http.Headers and Windows.Web.Http.Filters namespaces provide a programming interface for Universal Windows Platform (UWP) apps that act as an HTTP client to perform basic GET requests or implement more advanced HTTP functionality listed below.
Methods for common verbs (DELETE, GET, PUT, and POST). Each of these requests are sent as an asynchronous operation.
Support for common authentication settings and patterns.
Access to Secure Sockets Layer (SSL) details on the transport.
Ability to include customized filters in advanced apps.
Ability to get, set, and delete cookies.
HTTP Request progress info available on asynchronous methods.
The Windows.Web.Http.HttpRequestMessage class represents an HTTP request message sent by Windows.Web.Http.HttpClient. The Windows.Web.Http.HttpResponseMessage class represents an HTTP response message received from an HTTP request. HTTP messages are defined in RFC 2616 by the IETF.
The Windows.Web.Http namespace represents HTTP content as the HTTP entity body and headers including cookies. HTTP content can be associated with an HTTP request or an HTTP response. The Windows.Web.Http namespace provides a number of different classes to represent HTTP content.
- HttpBufferContent. Content as a buffer
- HttpFormUrlEncodedContent. Content as name and value tuples encoded with the application/x-www-form-urlencoded MIME type
- HttpMultipartContent. Content in the form of the multipart/* MIME type.
- HttpMultipartFormDataContent. Content that is encoded as the multipart/form-data MIME type.
- HttpStreamContent. Content as a stream (the internal type is used by the HTTP GET method to receive data and the HTTP POST method to upload data)
- HttpStringContent. Content as a string.
- IHttpContent — A base interface for developers to create their own content objects
The code snippet in the «Send a simple GET request over HTTP» section uses the HttpStringContent class to represent the HTTP response from an HTTP GET request as a string.
The Windows.Web.Http.Headers namespace supports creation of HTTP headers and cookies, which are then associated as properties with HttpRequestMessage and HttpResponseMessage objects.
Send a simple GET request over HTTP
As mentioned earlier in this article, the Windows.Web.Http namespace allows UWP apps to send GET requests. The following code snippet demonstrates how to send a GET request to http://www.contoso.com using the Windows.Web.Http.HttpClient class and the Windows.Web.Http.HttpResponseMessage class to read the response from the GET request.
POST binary data over HTTP
The C++/WinRT code example below illustrates using form data and a POST request to send a small amount of binary data as a file upload to a web server. The code uses the HttpBufferContent class to represent the binary data, and the HttpMultipartFormDataContent class to represent the multi-part form data.
Calling get (as seen in the code example below) isn’t appropriate for a UI thread. For the correct technique to use in that case, see Concurrency and asynchronous operations with C++/WinRT.
To POST the contents of an actual binary file (rather than the explicit binary data used above), you’ll find it easier to use an HttpStreamContent object. Construct one and, as the argument to its constructor, pass the value returned from a call to StorageFile.OpenReadAsync. That method returns a stream for the data inside your binary file.
Also, if you’re uploading a large file (larger than about 10MB), then we recommend that you use the Windows Runtime Background Transfer APIs.
POST JSON data over HTTP
The following example posts some JSON to an endpoint, then writes out the response body.
Exceptions in Windows.Web.Http
An exception is thrown when an invalid string for a the Uniform Resource Identifier (URI) is passed to the constructor for the Windows.Foundation.Uri object.
In C# and Visual Basic, this error can be avoided by using the System.Uri class in the .NET 4.5 and one of the System.Uri.TryCreate methods to test the string received from a user before the URI is constructed.
In C++, there is no method to try and parse a string to a URI. If an app gets input from the user for the Windows.Foundation.Uri, the constructor should be in a try/catch block. If an exception is thrown, the app can notify the user and request a new hostname.
The Windows.Web.Http lacks a convenience function. So an app using HttpClient and other classes in this namespace needs to use the HRESULT value.
In apps using C++/WinRT, the winrt::hresult_error struct represents an exception raised during app execution. The winrt::hresult_error::code function returns the HRESULT assigned to the specific exception. The winrt::hresult_error::message function returns the system-provided string that is associated with the HRESULT value. For more info, see Error handling with C++/WinRT
Possible HRESULT values are listed in the Winerror.h header file. Your app can filter on specific HRESULT values to modify app behavior depending on the cause of the exception.
In apps using the .NET FrameworkВ 4.5 in C#, VB.NET, the System.Exception represents an error during app execution when an exception occurs. The System.Exception.HResult property returns the HRESULT assigned to the specific exception. The System.Exception.Message property returns the message that describes the exception.
C++/CX has been superseded by C++/WinRT. But in apps using C++/CX, the Platform::Exception represents an error during app execution when an exception occurs. The Platform::Exception::HResult property returns the HRESULT assigned to the specific exception. The Platform::Exception::Message property returns the system-provided string that is associated with the HRESULT value.
For most parameter validation errors, the HRESULT returned is E_INVALIDARG. For some illegal method calls, the HRESULT returned is E_ILLEGAL_METHOD_CALL.
HttpClient HttpClient
Важные API Important APIs
Используйте HttpClient и остаток API пространства имен Windows.Web.Http для отправки и получения данных по протоколам HTTP 2.0 и HTTP 1.1. Use HttpClient and the rest of the Windows.Web.Http namespace API to send and receive information using the HTTP 2.0 and HTTP 1.1 protocols.
Обзор HttpClient и пространства имен Windows.Web.Http Overview of HttpClient and the Windows.Web.Http namespace
Классы в пространстве имен Windows.Web.Http и связанных с ним пространствах имен Windows.Web.Http.Headers и Windows.Web.Http.Filters предоставляют программный интерфейс для приложений UWP, действующих как клиент HTTP, для выполнения базовых запросов GET или реализации более сложных функций HTTP, перечисленных ниже. The classes in the Windows.Web.Http namespace and the related Windows.Web.Http.Headers and Windows.Web.Http.Filters namespaces provide a programming interface for Universal Windows Platform (UWP) apps that act as an HTTP client to perform basic GET requests or implement more advanced HTTP functionality listed below.
Методы для распространенных команд (DELETE, GET, PUT и POST). Methods for common verbs (DELETE, GET, PUT, and POST). Отправка каждого из этих запросов представляет собой асинхронную операцию. Each of these requests are sent as an asynchronous operation.
поддержка распространенных параметров и схем проверки подлинности; Support for common authentication settings and patterns.
доступ к сведениям о передаче по протоколу SSL; Access to Secure Sockets Layer (SSL) details on the transport.
возможность включать пользовательские фильтры в расширенные приложения; Ability to include customized filters in advanced apps.
возможность получать, задавать и удалять файлы cookie; Ability to get, set, and delete cookies.
информация о ходе выполнения HTTP-запроса доступна для асинхронных методов. HTTP Request progress info available on asynchronous methods.
Класс Windows.Web.Http.HttpRequestMessage представляет сообщение HTTP-запроса, отправляемое объектом Windows.Web.Http.HttpClient. The Windows.Web.Http.HttpRequestMessage class represents an HTTP request message sent by Windows.Web.Http.HttpClient. Класс Windows.Web.Http.HttpResponseMessage представляет сообщение HTTP-ответа, полученного в ответ на HTTP-запрос. The Windows.Web.Http.HttpResponseMessage class represents an HTTP response message received from an HTTP request. Сообщения HTTP определены IETF в RFC 2616. HTTP messages are defined in RFC 2616 by the IETF.
Пространство имен Windows.Web.Http представляет содержимое HTTP в виде основного текста и заголовков содержимого, включая файлы cookie. The Windows.Web.Http namespace represents HTTP content as the HTTP entity body and headers including cookies. Содержимое HTTP может связываться с HTTP-запросом или HTTP-ответом. HTTP content can be associated with an HTTP request or an HTTP response. В пространстве имен Windows.Web.Http доступно несколько классов для представления содержимого HTTP. The Windows.Web.Http namespace provides a number of different classes to represent HTTP content.
- HttpBufferContent. HttpBufferContent. Содержимое в виде буфера Content as a buffer
- HttpFormUrlEncodedContent. HttpFormUrlEncodedContent. Содержимое как кортежи «имя-значение», закодированные типом MIME application/x-www-form-urlencoded Content as name and value tuples encoded with the application/x-www-form-urlencoded MIME type
- HttpMultipartContent. HttpMultipartContent. Содержимое в форме типа MIME *multipart/* _. Content in the form of the *multipart/* _ MIME type.
- _ HttpMultipartFormDataContent*. _ HttpMultipartFormDataContent*. Содержимое, закодированное как тип MIME multipart/form-data. Content that is encoded as the multipart/form-data MIME type.
- HttpStreamContent. HttpStreamContent. Содержимое как поток (внутренний тип, который используется HTTP-методом GET для получения данных и HTTP-методом POST для отправки данных) Content as a stream (the internal type is used by the HTTP GET method to receive data and the HTTP POST method to upload data)
- HttpStringContent. HttpStringContent. Содержимое в виде строки. Content as a string.
- IHttpContent — базовый интерфейс для разработчиков, создающих собственные объекты содержимого. IHttpContent — A base interface for developers to create their own content objects
Фрагмент кода в разделе «Отправка простого запроса GET через HTTP» использует класс HttpStringContent для представления ответа HTTP из запроса GET HTTP в виде строки. The code snippet in the «Send a simple GET request over HTTP» section uses the HttpStringContent class to represent the HTTP response from an HTTP GET request as a string.
Пространство имен Windows.Web.Http.Headers поддерживает создание заголовков HTTP и файлов cookie, которые затем связываются в качестве свойств с объектами HttpRequestMessage и HttpResponseMessage. The Windows.Web.Http.Headers namespace supports creation of HTTP headers and cookies, which are then associated as properties with HttpRequestMessage and HttpResponseMessage objects.
Отправка простого запроса GET через HTTP Send a simple GET request over HTTP
Как упоминалось ранее в этой статье, пространство имен Windows.Web.Http позволяет приложениям UWP отправлять запросы GET. As mentioned earlier in this article, the Windows.Web.Http namespace allows UWP apps to send GET requests. Следующий фрагмент кода демонстрирует, как отправлять запрос GET на адрес http://www.contoso.com с помощью класса Windows.Web.Http.HttpClient и класса Windows.Web.Http.HttpResponseMessage для чтения ответа из запроса GET. The following code snippet demonstrates how to send a GET request to http://www.contoso.com using the Windows.Web.Http.HttpClient class and the Windows.Web.Http.HttpResponseMessage class to read the response from the GET request.
Использование запроса POST для отправки двоичных данных по HTTP POST binary data over HTTP
Пример кода C++/WinRT ниже демонстрирует использование данных формы и запроса POST для отправки небольшого объема двоичных данных в виде файла, передаваемого на веб-сервер. The C++/WinRT code example below illustrates using form data and a POST request to send a small amount of binary data as a file upload to a web server. В этом коде класс HttpBufferContent представляет двоичные данные, а класс HttpMultipartFormDataContent — данные составной формы. The code uses the HttpBufferContent class to represent the binary data, and the HttpMultipartFormDataContent class to represent the multi-part form data.
Использовать вызов get (как показано в примере кода ниже) недопустимо для потока пользовательского интерфейса. Calling get (as seen in the code example below) isn’t appropriate for a UI thread. В таком случае используйте способ, описанный в статье Concurrency and asynchronous operations with C++/WinRT (Параллелизм и синхронные операций с помощью C++/WinRT). For the correct technique to use in that case, see Concurrency and asynchronous operations with C++/WinRT.
Чтобы передать содержимое двоичного файла (а не явные двоичные данные, как это было сделано выше) с помощью запроса POST, воспользуйтесь объектом HttpStreamContent. To POST the contents of an actual binary file (rather than the explicit binary data used above), you’ll find it easier to use an HttpStreamContent object. Создайте его и передайте значение, возвращенное вызовом, в виде аргумента для конструктора в метод StorageFile.OpenReadAsync. Construct one and, as the argument to its constructor, pass the value returned from a call to StorageFile.OpenReadAsync. Этот метод возвращает поток для данных в вашем двоичном файле. That method returns a stream for the data inside your binary file.
Кроме того, если вы передаете файл большого размера (больше 10 МБ), мы рекомендуем использовать интерфейсы API среды выполнения Windows для передачи в фоновом режиме. Also, if you’re uploading a large file (larger than about 10MB), then we recommend that you use the Windows Runtime Background Transfer APIs.
Передача данных JSON с помощью запроса POST по HTTP POST JSON data over HTTP
В следующем примере данные JSON передаются на конечную точку, а затем выводится текст ответа. The following example posts some JSON to an endpoint, then writes out the response body.
Исключения в Windows.Web.Http Exceptions in Windows.Web.Http
Исключение создается, если конструктору для объекта Windows.Foundation.Uri передается неправильная строка универсального кода ресурса (URI). An exception is thrown when an invalid string for a the Uniform Resource Identifier (URI) is passed to the constructor for the Windows.Foundation.Uri object.
В C# и Visual Basic можно избежать этой ошибки, используя класс System.Uri из платформы .NET 4.5 и один из методов System.Uri.TryCreate, чтобы перед составлением URI проверить строку, полученную от пользователя приложения. In C# and Visual Basic, this error can be avoided by using the System.Uri class in the .NET 4.5 and one of the System.Uri.TryCreate methods to test the string received from a user before the URI is constructed.
В C++ нет метода для преобразования строки в код URI. In C++, there is no method to try and parse a string to a URI. Если пользователь вводит в приложение данные Windows.Foundation.Uri, конструктор должен находиться в блоке try/catch. If an app gets input from the user for the Windows.Foundation.Uri, the constructor should be in a try/catch block. Если вызывается исключение, приложение может уведомить об этом пользователя и запросить новое имя узла. If an exception is thrown, the app can notify the user and request a new hostname.
В пространстве имен Windows.Web.Http отсутствует удобная функция для обработки исключений. The Windows.Web.Http lacks a convenience function. Поэтому приложение, использующее класс HttpClient и другие классы из этого пространства имен, должно использовать значение HRESULT. So an app using HttpClient and other classes in this namespace needs to use the HRESULT value.
В приложениях, использующих C++ /WinRT, структура winrt::hresult_error представляет исключение, возникающее во время выполнения приложений. In apps using C++/WinRT, the winrt::hresult_error struct represents an exception raised during app execution. Функция winrt::hresult_error::code возвращает значение HRESULT, назначенное определенному исключению. The winrt::hresult_error::code function returns the HRESULT assigned to the specific exception. Функция winrt::hresult_error::message возвращает строку, которая предоставляется системой и связывается со значением HRESULT. The winrt::hresult_error::message function returns the system-provided string that is associated with the HRESULT value. Дополнительные сведения см. в статье Обработка ошибок в C++/WinRT. For more info, see Error handling with C++/WinRT
Возможные значения HRESULT перечислены в файле заголовка Winerror.h. Possible HRESULT values are listed in the Winerror.h header file. Ваше приложение может фильтровать полученные данные по определенному значению перечисления HRESULT, чтобы действовать в зависимости от причины исключения. Your app can filter on specific HRESULT values to modify app behavior depending on the cause of the exception.
В приложениях, использующих .NET Framework 4.5 и написанных на C# или VB.NET, объект System.Exception представляет ошибку во время выполнения приложения, когда возникает исключение. In apps using the .NET Framework 4.5 in C#, VB.NET, the System.Exception represents an error during app execution when an exception occurs. Свойство System.Exception.HResult возвращает значение HRESULT, назначенное определенному исключению. The System.Exception.HResult property returns the HRESULT assigned to the specific exception. Свойство System.Exception.Message возвращает сообщение с описанием исключения. The System.Exception.Message property returns the message that describes the exception.
C++/CX замещается C++/WinRT. C++/CX has been superseded by C++/WinRT. Но в приложениях на C++/CX объект Platform::Exception представляет ошибку во время выполнения приложения, когда возникает исключение. But in apps using C++/CX, the Platform::Exception represents an error during app execution when an exception occurs. Свойство Platform::Exception::HResult возвращает значение HRESULT, назначенное определенному исключению. The Platform::Exception::HResult property returns the HRESULT assigned to the specific exception. Свойство Platform::Exception::Message возвращает строку, которая предоставляется системой и связывается со значением HRESULT. The Platform::Exception::Message property returns the system-provided string that is associated with the HRESULT value.
Для многих ошибок при проверке параметров HRESULT возвращает значение E_INVALIDARG. For most parameter validation errors, the HRESULT returned is E_INVALIDARG. Для некоторых непредусмотренных вызовов методов возвращаемым значением HRESULT будет E_ILLEGAL_METHOD_CALL. For some illegal method calls, the HRESULT returned is E_ILLEGAL_METHOD_CALL.