Http post windows api

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
Читайте также:  Linux переменная окружения display

Фрагмент кода в разделе «Отправка простого запроса 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.

Читайте также:  Обновления для windows 10 версии 1903 не устанавливается

В 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.

How to make an HTTP POST web request

Canonical
How can I make an HTTP request and send some data using the POST method?

I can do a GET request, but I have no idea of how to make a POST request.

Читайте также:  Shell для windows phone

15 Answers 15

There are several ways to perform HTTP GET and POST requests:

Method A: HttpClient (Preferred)

Available in: .NET Framework 4.5+ , .NET Standard 1.1+ , .NET Core 1.0+ .

It is currently the preferred approach, and is asynchronous and high performance. Use the built-in version in most cases, but for very old platforms there is a NuGet package.

Setup

It is recommended to instantiate one HttpClient for your application’s lifetime and share it unless you have a specific reason not to.

Method B: Third-Party Libraries

It is a newer library sporting a fluent API, testing helpers, uses HttpClient under the hood, and is portable. It is available via NuGet.

Available in: .NET Framework 1.1+ , .NET Standard 2.0+ , .NET Core 1.0+ . In .NET Core, it is mostly for compatibility — it wraps HttpClient , is less performant, and won’t get new features.

This is a wrapper around HttpWebRequest . Compare with HttpClient .

Available in: .NET Framework 1.1+ , NET Standard 2.0+ , .NET Core 2.0+

Simple GET request

Simple POST request

This is a complete working example of sending/receiving data in JSON format, I used Visual Studio 2013 Express Edition:

There are some really good answers on here. Let me post a different way to set your headers with the WebClient(). I will also show you how to set an API key.

This solution uses nothing but standard .NET calls.

  • In use in an enterprise WPF application. Uses async/await to avoid blocking the UI.
  • Compatible with .NET 4.5+.
  • Tested with no parameters (requires a «GET» behind the scenes).
  • Tested with parameters (requires a «POST» behind the scenes).
  • Tested with a standard web page such as Google.
  • Tested with an internal Java-based webservice.

To call with no parameters (uses a «GET» behind the scenes):

To call with parameters (uses a «POST» behind the scenes):

Simple (one-liner, no error checking, no wait for response) solution I’ve found so far:

Use with caution!

If you like a fluent API you can use Tiny.RestClient. It’s available at NuGet.

When using Windows.Web.Http namespace, for POST instead of FormUrlEncodedContent we write HttpFormUrlEncodedContent. Also the response is type of HttpResponseMessage. The rest is as Evan Mulawski wrote down.

Why is this not totally trivial? Doing the request is not and especially not dealing with the results and seems like there are some .NET bugs involved as well — see Bug in HttpClient.GetAsync should throw WebException, not TaskCanceledException

I ended up with this code:

This will do a GET or POST depends if postBuffer is null or not

if Success is true the response will then be in ResponseAsString

if Success is false you can check WebExceptionStatus , HttpStatusCode and ResponseAsString to try to see what went wrong.

Yet another way of doing it:

This way you can easily post a stream.

In .net core you can make post-call with following code, here I added some extra features to this code so can make your code work behind a proxy and with network credentials if any, also here I mention that you can change the encoding of your message. I hope this explains all and help you in coding.

Here’s what i use in .NET 4.8 to make a HTTP POST request. With this code one can send multiple POST requests at a time Asynchronously. At the end of each request an event is raised. And also at the end of all request another event is raised.

The one bellow is the core class:

the AeonLabs.Envoriment is a class with a collection or fields and properties.

And the one bellow is for making a POST request:

Оцените статью