C как сделать get запрос
Перейти к содержимому

C как сделать get запрос

  • автор:

C# HttpClient

C# HttpClient tutorial shows how to create HTTP requests with HttpClient in C#. In the examples, we create simple GET and POST requests.

The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web.

HttpClient is a base class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI.

Advertisements HTTP request methods

  • GET — requests a representation of the specified resource
  • HEAD — identical to a GET request, but without the response body
  • POST — sends data to a resource, often causing state change or side effects
  • PUT — creates a resource or updates an existing resource
  • DELETE — deletes the specified resource
  • CONNECT — starts two-way communications with the requested resource
  • OPTION — describes the communication options for the target resource
  • TRACE — returns the full HTTP request back for debugging purposes
  • PATCH — performs partial modifications to the resource

C# HttpClient status code

  • Informational responses (100–199)
  • Successful responses (200–299)
  • Redirects (300–399)
  • Client errors (400–499)
  • Server errors (500–599)

The example creates a GET request to a small website. We get the status code of the request.

A new HttpClient is created.

The GetAsync method sends a GET request to the specified Uri as an asynchronous operation. The await operator suspends the evaluation of the enclosing async method until the asynchronous operation completes. When the asynchronous operation completes, the await operator returns the result of the operation, if any.

We get the 200 OK status code; the website is up.

Advertisements C# HttpClient GET request

The GET method requests a representation of the specified resource.

The example issues a GET request to the webcode.me website. It outputs the simple HTML code of the home page.

The GetStringAsync sends a GET request to the specified Uri and returns the response body as a string in an asynchronous operation.

C# HttpClient HEAD request

The HTTP HEAD method requests the headers that are returned if the specified resource would be requested with an HTTP GET method.

The example issues a HEAD request.

These are the header fields of the response.

Advertisements C# HttpClient User-Agent

The User-Agent request header is a string that lets servers and network peers identify the application, operating system, vendor, and/or version of the requesting user agent.

The example sets a User-Agent header for its GET request. The requested resource simply returns the client’s User-Agent string.

C# HttpClient HttpRequestMessage

The HttpRequestMessage represents a request message.

In the example, we manually build the request message.

A GET request message is created with HttpRequestMessage and sent with SendAsync .

We read the content of the response with ReadAsStringAsync .

Advertisements C# HttpClient query strings

Query string is a part of the URL which is used to add some data to the request for the resource. It is often a sequence of key/value pairs. It follows the path and starts with the ? character.

The query string is built with the UriBuilder .

C# HttpClient timeout

Currently, the http request times out after 100 s. To set a different timeout, we can use the TimeOut property.

In this code snippet, we set the timeout to 3 minutes.

Advertisements C# HttpClient multiple async requests

In the following example, we generate multiple asynchronous GET requests.

We download the given web pages asynchronously and print their HTML title tags.

The GetStringAsync sends a GET request to the specified url and returns the response body as a string in an asynchronous operation. It returns a new task; in C# a task represents an asynchronous operation.

The Task.WaitAll waits for all of the provided tasks to complete execution.

The await unwraps the result value.

Advertisements C# HttpClient POST request

The HTTP POST method sends data to the server. The type of the body of the request is indicated by the Content-Type header.

We need to add the Newtonsoft.Json package to process JSON data.

In the example, we send a POST request to https://httpbin.org/post website, which is an online testing service for developers.

We turn an object into a JSON data with the help of the Newtonsoft.Json package.

We send an asynchronous POST request with the PostAsync method.

We read the returned data and print it to the console.

Advertisements C# HttpClient JSON request

JSON (JavaScript Object Notation) is a lightweight data-interchange format. This format is easy for humans to read and write and for machines to parse and generate. It is a less verbose and more readable alternative to XML. The official Internet media type for JSON is application/json .

The example generates a GET request to to Github. It finds out the top contributors of the Symfony framework. It uses the Newtonsoft.Json to work with JSON.

In the request header, we specify the user agent.

In the accept header value, we tell that JSON is an acceptable response type.

We generate a request and read the content asynchronously.

We transform the JSON response into a list of Contributor objects with the JsonConvert.DeserializeObject method.

Advertisements C# HttpClient POST form data

POST requests are often sent via a post form. The type of the body of the request is indicated by the Content-Type header. The FormUrlEncodedContent is a container for name/value tuples encoded using application/x-www-form-urlencoded MIME type.

The example sends a form POST requests using FormUrlEncodedContent .

C# HttpClient proxy

A proxy is an intermediary between a client requesting a resource and the server providing that resource.

https://amdy.su/wp-admin/options-general.php?page=ad-inserter.php#tab-8

The example creates a web request through a proxy. C# uses WebProxy to set up a proxy server.

Advertisements C# HttpClient download image

The GetByteArrayAsync sends a GET request to the specified Uri and returns the response body as a byte array in an asynchronous operation.

In the example, we download an image from the webcode.me website. The image is written to the user’s Documents folder.

The GetByteArrayAsync returns the image as an array of bytes.

We determine the Documents folder with the GetFolderPath method.

The bytes are written to the disk with the File.WriteAllBytes method.

C# HttpClient streaming

Streaming is a method of transmitting of data in a continuous stream that can be processed by the receiving computer before the entire file has been completely sent.

In the example, we download a NetBSD USB image using streaming.

With the HttpCompletionOption.ResponseHeadersRead option the async operation should complete as soon as a response is available and headers are read. The content is not read yet. The method will just read the headers and returns the control back.

The ReadAsStreamAsync methods erialize the HTTP content and return a stream that represents the content as an asynchronous operation.

The data is copied continuously to the file stream.

Advertisements C# HttpClient Basic authentication

In HTTP protocol, basic access authentication is a method for an HTTP user agent (such as a web browser or a console application) to provide a user name and password when making a request. In basic HTTP authentication, a request contains a header field in the form of Authorization: Basic <credentials> , where credentials is the base64 encoding of id and password joined by a single colon : .

HTTP Basic authentication is the simplest technique for enforcing access controls to web resources. It does not require cookies, session identifiers, or login pages; rather, HTTP Basic authentication uses standard fields in the HTTP header.

Протокол HTTP. Класс HttpClient и HttpListener

В этой главе рассмотрим отправку запросов с помощью класса HttpClient . Но в начале вкратце посмотрим, что представляет протокол Http. HTTP ( Hypertext Transfer Protocol ) представляет протокол для запроса ресурсов с веб-сервера. Когда мы обращаемся в веб-браузере к каким-либо веб-сайтами, мы как раз используем протокол HTTP.

В .NET основной функционал по работе с протоколом HTTP сосредоточен в простанстве имен System.Net.Http , среди основных классов в котором следует отметить класс HttpClient (класс, который позволяет отправлять запросы к веб-ресурсам) и класс HttpListener , который выполняет роль веб-сервера. Но перед рассмотрением этих классов, следует вкратце рассмотреть базовые моменты протокола HTTP.

Методы HTTP

Когда клиент собирается сделать запрос на сервер, данный клиент должен определить метод ответа сервера на запрос. Метод HTTP описывает действия сервера при обработке запроса. Основные из этих методов:

OPTIONS : возвращает список остальных методов HTTP, которые поддерживает сервер для указанного адреса URL

TRACE : служебный метод, который просто повторяет исходный запрос, полученный сервером. Полезен для идентификации любых изменений, внесенных в запрос объектами в сети, пока запрос находится в пути.

CONNECT : устанавливают туннель TCP/IP между исходным хостом и удаленным хостом.

GET : извлекает копию ресурса по URL-адресу, на который был отправлен HTTP-запрос.

HEAD : так же как и GET, извлекает копию ресурса по URL, только ожидает получения одних заголовков без тела ответа

POST : предназначен для отправки данных в теле запроса для их сохранения в виде нового ресурса на сервере

PUT : предназначен для отправки данных в теле запроса для изменения уже имеющегося ресурса на сервере

PATCH : предназначен для отправки данных в теле запроса для частичного изменения уже имеющегося ресурса на сервереL

How to make an HTTP get request in C without libcurl?

I want to write a C program to generate a Get Request without using any external libraries. Is this possible using only C libraries, using sockets ? I’m thinking of crafting a http packet(using proper formatting) and sending it to the server. Is this the only possible way or is there a better way ?

Ciro Santilli OurBigBook.com's user avatar

4 Answers 4

Using BSD sockets or, if you’re somewhat limited, say you have some RTOS, some simpler TCP stack, like lwIP, you can form the GET/POST request.

There are a number of open-source implementations. See the «happyhttp» as a sample ( http://scumways.com/happyhttp/happyhttp.html ). I know, it is C++, not C, but the only thing that is «C++-dependant» there is a string/array management, so it is easily ported to pure C.

Beware, there are no «packets», since HTTP is usually transfered over the TCP connection, so technically there is only a stream of symbols in RFC format. Since http requests are usually done in a connect-send-disconnect manner, one might actually call this a «packet».

Basically, once you have an open socket (sockfd) «all» you have to do is something like

Viktor Latypov's user avatar

40 lines of code. Thank you for ensure the code works. (I mean strictly about test before post). THANK YOU.

POSIX 7 minimal runnable example

Get http://example.com and output to stdout:

We see something like:

After printing the reply, this command hangs for most servers until timeout, and that is expected:

  • either server or client must close the connection
  • we (client) are not doing it
  • most HTTP servers leave the connection open until a timeout expecting further requests, e.g. JavaScript, CSS and images following an HTML page
  • we could parse the response, and close when Content-Length bytes are read, but we didn’t for simplicity. What HTTP response headers are required says that if Content-Length is not sent, the server can just close to determine length.

We could however make the host close by passing adding the HTTP 1.1 standard header Connection: close to the server:

The connection part also works with the IP:

however, the reply is an error, because we are not setting the Host: properly in our program, and that is required in HTTP 1.1.

Tested on Ubuntu 18.04.

Why doesn’t POSIX supply wget ?

It is a great shame, considering that all main capabilities are in place! Is wget or similar programs always available on POSIX systems?

Server examples

  • minimal POSIX C example: Send and Receive a file in socket programming in Linux with C/C++ (GCC/G++)
  • minimal Android Java example: how to create Socket connection in Android?

Ciro Santilli OurBigBook.com's user avatar

“Without any external libraries” strictly speaking would exclude libc as well, so you’d have to write all syscalls yourself. I doubt you mean it that strict, though. If you don’t want to link to another library, and don’t want to copy source code from another library into your application, then directly dealing with the TCP stream using the socket API is your best approach.

Creating the HTTP request and sending it over a TCP socket connection is easy, as is reading the answer. It’s parsing the answer which is going to be real tricky, particularly if you aim to support a reasonably large portion of the standard. Things like error pages, redirects, content negotiation and so on can make our life quite hard if you’re talking to arbitrary web servers. If on the other hand the server is known to be well-behaved, and a simple error message is all right for any unexpected server response, then that is reasonably simple as well.

Try Socket Programming, the below C++ code issues a simple GET Request to specified host and prints the response header and content

Tested in Windows 10

To compile (using g++) :

-lws2_32 specifies the linker to link with winsock dlls

    The Overflow Blog
Linked
Related
Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.6.13.43492

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Создание HTTP-запросов на C++

В этой статье я покажу вам, как создавать HTTP-запросы к REST-серверу с помощью библиотеки C++ Request, написанной Ху Нгуеном. При её написании мистер Нгуен во многом ориентировался на принципы проектирования из Python Requests, поэтому для тех, кто использовал или знаком с Python Requests, C++ Requests окажется вполне понятна.

Для демонстрации клиентского кода нам потребуется веб-сервер, к которому можно будет отправлять запрос, так что в данном случае мы реализуем CRUD API (Create, Read, Update, Delete) с помощью ASP.NET Web API 2. Сам сервер не представляет основную идею статьи, но структуру веб-API я всё равно поясню. Если же вас код сервера не интересует (вы не используете ASP.NET), тогда можете сразу переходить к разделу клиента.

▍ ASP.NET Web API

Я не стану подробно расписывать настройку проекта веб-API на ASP.NET. Заинтересованный читатель может обратиться к этому и этому руководствам от Microsoft.

Данный веб-API построен по схеме МVC (модель-представление-контроллер). Модель отвечает за данные, обычно это классы, которые определяют расположение данных в хранилище. Представление отвечает за, собственно, представление этих данных пользователю, а контроллер занимается бизнес-логикой.

Строго говоря, чистый веб-API сервер ASP.NET не предоставляет HTML-страницы, а значит, слоя представления не имеет. В нашем примере в качестве модели данных выступает класс Product .

В ProductsController класс Product хранится в непостоянном static Dictionary , то есть после выключения сервера API данные будут утрачиваться. Но такого решения будет достаточно для нашей демонстрации без участия БД.

Далее идёт метод Create , отвечающий за создание объекта Product для сохранения в словаре. Атрибут [FromBody] означает, что элемент Product будет заполнен содержимым из тела запроса.

Для проверки кода я использую команду curl . Если у вас установлен Postman, то можете использовать его. Я же старомодный парень, поэтому предпочитаю непосредственно curl .

  • -X указывает HTTP-глагол POST , соответствующий методу create или update ;
  • вторым аргументом идёт URL, по которому должен отправиться запрос;
  • -H указывает HTTP-заголовки. Мы отправляем строку JSON, значит, устанавливаем ‘Content-Type’ на ‘application/json’ ;
  • -d указывает тело запроса. Здесь ясно видно, что ключи словаря JSON в точности соответствуют членам Product .

Соответствующие команды curl извлекают все либо один Product на основе переданного id (равен 1 ). Аргументы командной строки аналогичны описанным выше, так что их я пропущу.

Первый результат заключён в [] , потому что первая команда возвращает коллекцию объектов Product , но в нашем случае пока в ней всего один товар.

В завершение нужно обновить методы Update и Delete . Разница между HTTP-глаголами POST и PUT в том, что PUT выполняет исключительно обновление, а POST создаёт объект в случае его отсутствия, но при этом также может использоваться и для обновления.

Соответствующие команды curl обновляют и удаляют Product с id=1 .

Убедиться, что Product действительно был обновлён или удалён, можно с помощью приведённой выше команды curl для извлечения.

▍ Клиентский код C++

Наконец, мы добрались до основной сути статьи! Для того чтобы использовать C++ Request, вам нужно скопировать или скачать этот пакет отсюда и включить его заголовок cpr . В качестве альтернативы пользователи Visual C++ могут установить C++ Request через vcpkg. В vcpkg эта библиотека обозначена аббревиатурой cpr .

Для отправки запроса POST на создание Product мы помещаем его в cpr::Body в виде строкового литерала в формате JSON. Если не использовать строковый литерал, то придётся экранировать в строке JSON все двойные кавычки.

Сравнивая этот C++ код с командой curl , мы видим, какая и куда идёт информация.

После создания товара мы пробуем его извлечь:

Вывод будет такой же, как после команды curl , что вполне логично, поскольку в C++ Request для этого используется libcurl .

Весь код C++ для выполнения CRUD с помощью веб-API показан ниже вместе c выводом. Прежде чем его выполнять, убедитесь в работоспособности вашего веб-API.

Ниже, как и говорилось, показан вывод. Возвращаемый текст отображается, только когда операция CRUD его подразумевает, в противном случае показывается только статус. Например, операции Create/Update/Delete не возвращают никакой текст, поэтому отображается только их статус. В данном случае мы видим код 200, который означает успех HTTP-запроса.

Если вам нужно отправлять запросы с параметрами, как показано ниже, можете использовать cpr::Parameters .

Код C++ для вышеприведённого примера с URL:

Исходный код для этой статьи доступен на GitHub и в архиве cpprestexample-1.0.1.zip.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *