Windows forms http request

Практическое руководство. Отправка данных с помощью класса WebRequest How to: Send data by using the WebRequest class

В следующей процедуре описаны действия для отправки данных на сервер. The following procedure describes the steps to send data to a server. Эта процедура обычно используется для отправки данных на веб-страницу. This procedure is commonly used to post data to a Web page.

Отправка данных на сервер узла To send data to a host server

Создайте экземпляр WebRequest, вызвав метод WebRequest.Create с URI ресурса, например сценария или страницы ASP.NET, который принимает данные. Create a WebRequest instance by calling WebRequest.Create with the URI of a resource, such as a script or ASP.NET page, that accepts data. Пример: For example:

Платформа .NET Framework предоставляет связанные с определенным протоколом классы, производные от классов WebRequest и WebResponse, для URI, которые начинаются с http: , https: , ftp: и file: . The .NET Framework provides protocol-specific classes derived from the WebRequest and WebResponse classes for URIs that begin with http:, https:, ftp:, and file:.

Если нужно задать или считать связанные с определенным протоколом свойства, следует привести объект WebRequest или WebResponse к типу объекта, связанному с определенным протоколом. If you need to set or read protocol-specific properties, you must cast your WebRequest or WebResponse object to a protocol-specific object type. Дополнительные сведения см. в разделе Программирование подключаемых протоколов. For more information, see Programming pluggable protocols.

Укажите все необходимые значения свойств в объекте WebRequest . Set any property values that you need in your WebRequest object. Например, чтобы включить проверку подлинности, установите для свойства WebRequest.Credentials значение экземпляра класса NetworkCredential: For example, to enable authentication, set the WebRequest.Credentials property to an instance of the NetworkCredential class:

Укажите метод протокола, который разрешает отправлять данные с запросом, например метод POST HTTP: Specify a protocol method that permits data to be sent with a request, such as the HTTP POST method:

Задайте для свойства ContentLength число байт, включаемых в запрос. Set the ContentLength property to the number of bytes you’re including with your request. Пример: For example:

Присвойте свойству ContentType соответствующее значение. Set the ContentType property to an appropriate value. Пример: For example:

Получите поток, который содержит данные запроса, вызвав метод GetRequestStream. Get the stream that holds request data by calling the GetRequestStream method. Пример: For example:

Запишите данные в объект Stream, возвращенный методом GetRequestStream . Write the data to the Stream object returned by the GetRequestStream method. Пример: For example:

Закройте поток запроса, вызвав метод Stream.Close. Close the request stream by calling the Stream.Close method. Пример: For example:

Отправьте запрос на сервер, вызвав метод WebRequest.GetResponse. Send the request to the server by calling WebRequest.GetResponse. Этот метод возвращает объект, содержащий ответ сервера. This method returns an object containing the server’s response. Тип возвращенного объекта WebResponse определяется с помощью схемы URI запроса. The returned WebResponse object’s type is determined by the scheme of the request’s URI. Пример: For example:

Читайте также:  What services does linux have

Вы можете получить доступ к свойствам объекта WebResponse или привести этот объект к связанному с определенным протоколом экземпляру для считывания свойств для определенного протокола. You can access the properties of your WebResponse object or cast it to a protocol-specific instance to read protocol-specific properties.

Например, чтобы получить доступ к свойствам, связанным с протоколом HTTP, для HttpWebResponse, приведите объект WebResponse к ссылке HttpWebResponse. For example, to access the HTTP-specific properties of HttpWebResponse, cast your WebResponse object to an HttpWebResponse reference. В следующем примере кода показано, как отобразить свойство HttpWebResponse.StatusDescription, связанное с протоколом HTTP, которое было отправлено в ответе: The following code example shows how to display the HTTP-specific HttpWebResponse.StatusDescription property sent with a response:

Чтобы получить поток, содержащий данные ответа, отправленные сервером, вызовите метод WebResponse.GetResponseStream объекта WebResponse . To get the stream containing response data sent by the server, call the WebResponse.GetResponseStream method of your WebResponse object. Пример: For example:

После считывания данных из объекта ответа закройте его с помощью метода WebResponse.Close или закройте поток ответа с помощью метода Stream.Close. After you’ve read the data from the response object, either close it with the WebResponse.Close method or close the response stream with the Stream.Close method. Если не закрыть ответ или поток, у приложения могут закончиться подключения к серверу и оно может оказаться неспособным обрабатывать новые запросы. If you don’t close either the response or the stream, your application can run out of server connections and become unable to process additional requests. Так как при закрытии ответа метод WebResponse.Close вызывает Stream.Close , вызывать Close для объектов как потока, так и ответа не требуется (при этом выполнение такой операции не приведет к негативным последствиям). Because the WebResponse.Close method calls Stream.Close when it closes the response, it’s not necessary to call Close on both the response and stream objects, although doing so isn’t harmful. Пример: For example:

Пример Example

В следующем примере показана отправка данных на веб-сервер и считывание данных в ответе: The following example shows how to send data to a web server and read the data in its response:

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.

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 .

Читайте также:  Приложения для windows phone нокия люмия

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:

Практическое руководство. Запрос данных с помощью класса WebRequest How to: Request data by using the WebRequest class

Следующая процедура описывает шаги для запроса ресурсов, например веб-страницы или файла, с сервера. The following procedure describes the steps to request a resource, such as a Web page or a file, from a server. Ресурс должен быть определен универсальным кодом ресурса (URI). The resource must be identified by a URI.

Запрос данных с сервера узла To request data from a host server

Создайте экземпляр WebRequest путем вызова WebRequest.Create с URI ресурса. Create a WebRequest instance by calling WebRequest.Create with the URI of a resource. Пример: For example:

Платформа .NET Framework предоставляет связанные с определенным протоколом классы, производные от классов WebRequest и WebResponse, для URI, которые начинаются с http: , https: , ftp: и file: . The .NET Framework provides protocol-specific classes derived from the WebRequest and WebResponse classes for URIs that begin with http:, https:, ftp:, and file:.

Если нужно задать или считать связанные с определенным протоколом свойства, следует привести объект WebRequest или WebResponse к типу объекта, связанному с определенным протоколом. If you need to set or read protocol-specific properties, you must cast your WebRequest or WebResponse object to a protocol-specific object type. Дополнительные сведения см. в разделе Программирование подключаемых протоколов. For more information, see Programming pluggable protocols.

Читайте также:  Скайп заглушает все звуки windows 10

Укажите все необходимые значения свойств в объекте WebRequest . Set any property values that you need in your WebRequest object. Например, чтобы включить проверку подлинности, установите для свойства WebRequest.Credentials значение экземпляра класса NetworkCredential: For example, to enable authentication, set the WebRequest.Credentials property to an instance of the NetworkCredential class:

Отправьте запрос на сервер, вызвав метод WebRequest.GetResponse. Send the request to the server by calling WebRequest.GetResponse. Этот метод возвращает объект, содержащий ответ сервера. This method returns an object containing the server’s response. Тип возвращенного объекта WebResponse определяется с помощью схемы URI запроса. The returned WebResponse object’s type is determined by the scheme of the request’s URI. Пример: For example:

Вы можете получить доступ к свойствам объекта WebResponse или привести этот объект к связанному с определенным протоколом экземпляру для считывания свойств для определенного протокола. You can access the properties of your WebResponse object or cast it to a protocol-specific instance to read protocol-specific properties.

Например, чтобы получить доступ к свойствам, связанным с протоколом HTTP, для HttpWebResponse, приведите объект WebResponse к ссылке HttpWebResponse . For example, to access the HTTP-specific properties of HttpWebResponse, cast your WebResponse object to an HttpWebResponse reference. В следующем примере кода показано, как отобразить свойство HttpWebResponse.StatusDescription, связанное с протоколом HTTP, которое было отправлено в ответе: The following code example shows how to display the HTTP-specific HttpWebResponse.StatusDescription property sent with a response:

Чтобы получить поток, содержащий данные ответа, отправленные сервером, вызовите метод WebResponse.GetResponseStream. To get the stream containing response data sent by the server, call the WebResponse.GetResponseStream method. Пример: For example:

После считывания данных из объекта ответа закройте его с помощью метода WebResponse.Close или закройте поток ответа с помощью метода Stream.Close. After you’ve read the data from the response object, either close it with the WebResponse.Close method or close the response stream with the Stream.Close method. Если не закрыть объект ответа или поток, у приложения могут закончиться подключения к серверу и оно может оказаться неспособным обрабатывать новые запросы. If you don’t close either the response object or the stream, your application can run out of server connections and become unable to process additional requests. Так как при закрытии ответа метод WebResponse.Close вызывает Stream.Close , вызывать Close для объектов как потока, так и ответа не требуется (при этом выполнение такой операции не приведет к негативным последствиям). Because the WebResponse.Close method calls Stream.Close when it closes the response, it’s not necessary to call Close on both the response and stream objects, although doing so isn’t harmful. Пример: For example:

Пример Example

В следующем примере кода показано создание запроса к веб-серверу и считывание данных в ответе: The following code example shows how to create a request to a web server and read the data in its response:

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