Время на прочтение9 мин
Количество просмотров223K
Curl (client URL) — это инструмент командной строки на основе библиотеки libcurl для передачи данных с сервера и на сервер при помощи различных протоколов, в том числе HTTP, HTTPS, FTP, FTPS, IMAP, IMAPS, POP3, POP3S, SMTP и SMTPS. Он очень популярен в сфере автоматизации и скриптов благодаря широкому диапазону функций и поддерживаемых протоколов. В этой статье мы расскажем, как использовать curl в Windows на различных примерах.
▍ Установка в Windows
Во всех современных версиях Windows, начиная с Windows 10 (версия 1803) и Server 2019, исполняемый файл curl поставляется в комплекте, поэтому ручная установка не требуется. Чтобы определить местоположение curl и его версию в системе, можно использовать следующие команды:
where curl
curl --version
Определение местоположения и версии curl в Windows
Команда curl —version также выводит список протоколов и функций, поддерживаемых текущей версией curl. Как видно из показанного выше скриншота, к использованию встроенной утилиты curl всё готово. Если вместо этого отображается сообщение об ошибке, curl может быть недоступен потому, что вы используете более раннюю версию Windows (например, Windows 8.1 или Server 2016). В таком случае вам потребуется установить curl в Windows вручную.
▍ Синтаксис curl
Команда curl использует следующий синтаксис:
curl [options...] [url]
Инструмент поддерживает различные опции, которые мы рассмотрим ниже. Как и в любом инструменте командной строки, вы можете использовать для получения справки команду curl —help.
Получение справки при помощи команды curl
Для получения подробной справки можно использовать команду curl —help all. Справка разделена на категории, поэтому при помощи curl —help category можно просмотреть все темы.
Ознакомившись с синтаксисом curl, давайте рассмотрим различные способы применения этого инструмента на примерах.
▍ HTTP-запрос GET
При использовании curl с URL и без указания опций запрос по умолчанию использует метод GET протокола HTTP. Попробуйте выполнить такую команду:
curl https://4sysops.com
Приведённая выше команда по сути эквивалентна curl —request GET 4sysops.com, отправляющей запрос GET к 4sysops.com по протоколу HTTPS. Чтобы указать версию протокола HTTP (например, http/2), используйте опцию —http2:
curl --http2 https://4sysops.com
В случае URL, начинающихся с HTTPS, curl сначала пытается установить соединение http/2 и автоматически откатывается к http/1.1, если это не удаётся. Также он поддерживает другие методы, например, HEAD, POST, PUT и DELETE. Для использования этих методов вместе с командой curl нужно указать опцию —request (или -X), за которой следует указание метода. Стоит заметить, что список доступных методов зависит от используемого протокола.
▍ Получение информации об удалённом файле
Если вы администратор, то иногда вам могут быть интересны только заголовки HTTP. Их можно получить при помощи опции —head (или -I). Иногда URL может перенаправлять пользователя в другую точку. В таком случае опция —location (или -L) позволяет curl выполнять перенаправления. Также можно использовать —insecure (или -k), чтобы разрешить незащищённые подключения и избежать ошибок с сертификатом TLS в случае, если целевой URL использует самоподписанный сертификат. Пользуйтесь этой опцией только при абсолютной необходимости. Все эти три опции можно скомбинировать в одну краткую запись, как показано в следующей команде:
curl -kIL 4sysops.com
Опции просмотра заголовков запросов, включения незащищённого соединения и использования перенаправлений
Как можно заметить, такая краткая запись особенно полезна для комбинирования нескольких опций. Приведённая выше команда по сути эквивалентна команде curl —insecure —head —location 4sysops.com.
Опция —head (или -I) также даёт основную информацию об удалённом файле без его скачивания. Как показано на скриншоте ниже, при использовании curl с URL удалённого файла он отображает различные заголовки, дающие информацию об удалённом файле.
curl -IL https://curl.se/windows/dl-7.85.0_5/curl-7.85.0_5-win64-mingw.zip
Использование curl для просмотра основной информации удалённых файлов
Заголовок Content-Length обозначает размер файла (в байтах), Content-Type сообщает о типе медиафайла (например, image/png, text/html), Server обозначает тип серверного приложения (Apache, Gunicorn и так далее), Last-Modified показывает дату последнего изменения файла на сервере, а заголовок Accept-Ranges обозначает поддержку частичных запросов для скачивания от клиента, что по сути определяет возможность продолжения прерванной загрузки.
▍ Скачивание файла
Для скачивания файла и сохранения с тем же именем, что и на сервере, можно использовать curl с опцией —remote-name (или -O). Показанная ниже команда скачивает последнюю версию curl для Windows с официального сайта:
curl -OL https://curl.se/windows/latest.cgi?p=win64-mingw.zip
Скачивание файла с именем по умолчанию и индикатором прогресса
При необходимости для нахождения ресурса добавляется опция -L, разрешающая перенаправления. Если нужно сохранить файл с новым именем, используйте опцию —output (или -o). Кроме того, при использовании команды curl в скрипте может понадобиться отключить индикатор прогресса, что можно сделать при помощи опции —silent (или -s). Эти две опции можно скомбинировать:
curl -sLo curl.zip https://curl.se/windows/latest.cgi?p=win64-mingw.zip
Скачивание файла без индикатора и сохранение под произвольным именем
▍ Продолжение прерванного скачивания
Наличие Accept-Ranges: bytes в заголовке ответа в буквальном смысле обозначает, что сервер поддерживает скачивания с возможностью продолжения. Чтобы продолжить прерванное скачивание, можно использовать опцию —continue-at (или -C), получающую смещение (в байтах). Обычно указывать смещение непросто, поэтому curl предоставляет простой способ продолжения прерванной загрузки:
curl -OLC - https://releases.ubuntu.com/22.04/ubuntu-22.04.1-desktop-amd64.iso
Продолжение прерванного скачивания
Как видно из скриншота, я скачивал iso-файл Ubuntu, но скачивание было прервано. Затем я снова запустил команду curl с опцией -C, и передача продолжилась с того диапазона байтов, на котором была прервана. Знак минус (—) рядом с -C позволяет curl автоматически определить, как и где продолжить прерванное скачивание.
▍ Аутентификация с Curl
Также Curl поддерживает аутентификацию, что позволяет скачать защищённый файл, предоставив учётные данные при помощи опции —user (or -u), принимающей имя пользователя и пароль в формате username:password. Если не вводить пароль, curl попросит ввести его в режиме no-echo.
curl -u surender -OL https://techtutsonline.com/secretFiles/sample.zip
Скачивание файла с аутентификацией по имени пользователя и паролю
Если вы используете Basic authentication, то необходимо передать имя пользователя и пароль, а значит, воспользоваться защищённым протоколом наподобие HTTPS (вместо HTTP) или FTPS (вместо FTP). Если по каким-то причинам приходится использовать протокол без шифрования, то убедитесь, что вы используете способ аутентификации, не передающий учётные данные в виде простого текста (например, аутентификацию Digest, NTLM или Negotiate).
Также curl поддерживает использование файлов конфигурации .curlrc, _curlrc и .netrc, позволяющих задавать различные опции curl в файле, а затем добавлять файл в команду при помощи опции curl —config (или curl -K), что особенно полезно при написании скриптов.
▍ Выгрузка файла
Опция —upload-file (или -T) позволяет выгружать локальный файл на удалённый сервер. Показанная ниже команда выгружает файл из локальной системы на удалённый веб-сервер по протоколу FTPS:
curl -kT C:\Users\Surender\Downloads\sample1.zip -u testlab\surender ftps://192.168.0.80/awesomewebsite.com/files/
Выгрузка файла на удалённый сервер
Опция -k добавляется для устранения проблем с сертификатами на случай, если веб-сервер использует самоподписанный сертификат. Наклонная черта в конце URL сообщает curl, что конечная точка является папкой. Можно указать несколько имён файлов, например «{sample1.zip,sample2.zip}». Ниже показано, как с помощью одной команды curl можно выгрузить на сервер несколько файлов:
curl -kT sample[1-5].zip -u testlab\surender ftps://192.168.0.80/awesomewebsite.com/files/
Выгрузка нескольких файлов на сервер
▍ Последовательность команд
Как говорилось ранее, curl поддерживает различные методы в зависимости от используемого протокола. Дополнительные команды можно отправлять при помощи —quote (или -Q) для выполнения операции до или после обычной операции curl. Например, можно скачать файл с удалённого сервера по протоколу FTPS и удалить файл с сервера после успешного скачивания. Для этого нужно выполнить следующую команду:
curl -u testlab\surender -kO "ftps://192.168.0.80/awesomewebsite.com/files/sample1.zip" -Q "-DELE sample1.zip"
Удаление файла после успешного скачивания
В показанном выше примере я скачал файл sample1.zip с FTPS-сервера при помощи опции -O. После опции -Q я добавил минус (-) перед командой DELE, что заставляет curl отправить команду DELE sample1.zip сразу после успешного скачивания файла. Аналогично, если вы хотите отправить команду на сервер до выполнения операции curl, используйте плюс (+) вместо минуса.
▍ Изменение user-agent
Информация user-agent сообщает серверу тип клиента, отправляющего запрос. При отправке запроса curl на сервер по умолчанию используется user-agent curl/<version>. Если сервер настроен так, чтобы блокировать запросы curl, можно задать собственный user-agent при помощи опции —user-agent (или -A). Показанная ниже команда отправляет стандартный user-agent Google Chrome:
curl -kIA "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0" https://awesomewebsite.com/files/secretFile.zip
Использование собственного user-agent с командой curl, чтобы избежать блокировки сервером
На показанном выше скриншоте видно, что обычный запрос curl был отклонён веб-сервером (с ответом 403 Forbidden), но при передаче другого user-agent запрос выполняется успешно, возвращая ответ 200 OK.
▍ Отправка куки
По умолчанию запрос curl не отправляет и не сохраняет куки. Для записи куки можно использовать опцию —cookie-jar (или -c), а отправить куки можно опцией —cookie (or -b):
curl -c /path/cookie_file https://awesomewebsite.com/
curl -b /path/cookie_file https://awesomewebsite.com/
Первая команда записывает файл куки, а вторая отправляет куки с запросом curl. Также можно отправить куки в формате ‘name = value’:
curl -b 'session=abcxyz' -b 'loggedin=true' http://echo.hoppscotch.io
Отправка нескольких куки командой curl
Я воспользовался веб-сайтом echo.hoppscotch.io для демонстрации заголовков HTTP-запросов, которые обычно невидимы клиентам, отправляющим запрос. Если вы не хотите пользоваться этим веб-сайтом, то можете применить опцию –verbose (или -v) для отображения запроса в сыром виде (который отображает и заголовки запросов).
▍ Использование прокси-сервера
Если вы пользуетесь прокси-сервером для подключения к интернету, в curl можно указать прокси опцией —proxy (или -x). Если прокси-сервер требует аутентификации, то добавьте —proxy-user (или -U):
curl -x 192.168.0.250:8088 -U username:password https://awesomewebsite.com/
Прокси-сервер указывается в формате server:port, а пользователь прокси — в формате username:password. Можно не вводить пароль пользователя прокси, тогда curl попросит ввести его в режиме no-echo.
Использование прокси-сервера и аутентификации
▍ Дополнительные заголовки запросов
Иногда вместе с запросом к серверу необходимо отправить дополнительную информацию. В curl это можно сделать при помощи —header (или -H), как показано в следующей команде:
curl -vkIH "x-client-os: Windows 11 Enterprise (x64)" https://awesomewebsite.com
Указание дополнительных заголовков для запроса curl
Можно отправлять любую информацию, недоступную через стандартные заголовки HTTP-запросов. В этом примере я отправил название своей операционной системы. Также я добавил опцию -v для включения verbose-вывода, отображающего дополнительный заголовок, отправляемый вместе с каждым моим запросом curl.
▍ Отправка электронного письма
Так как curl поддерживает протокол SMTP, его можно использовать для отправки электронного письма. Показанная ниже команда позволяет отправить электронное письмо при помощи curl:
curl --insecure --ssl-reqd smtps://mail.yourdomain.com –-mail-from sender@yourdomain.com –-mail-rcpt receiver@company.com --user sender@yourdomain.com --upload-file email_msg.txt
Отправка электронного письма командой curl
Давайте вкратце перечислим использованные здесь опции:
- Опция —insecure (или -k) используется, чтобы избежать ошибки сертификата SSL. Мы уже применяли её ранее.
- Опция —ssl-reql используется для апгрейда соединения передачи простого текста до зашифрованного соединения, если оно поддерживается SMTP-сервером. Если вы уверены, что ваш SMTP-сервер поддерживает SSL, то можно использовать непосредственно имя сервера smtps (например, smtps://smtp.yourdomain.com), как показано на скриншоте.
- Опция —mail-from используется для указания адреса электронной почты отправителя.
- Опция mail-rcpt указывает адрес электронной почты получателя.
- Опция —user (или -u) отправляет имя пользователя для аутентификации, оно должно совпадать с адресом mail-from, потому что в противном случае письмо может быть отклонено или помечено как спам.
- Опция —upload-file (или -T) используется для указания файла, в котором находится отправляемое письмо.
На скриншоте ниже показано письмо, полученное мной во входящие:
Просмотр письма, отправленного с помощью curl
Это всего лишь несколько примеров использования curl — на самом деле их гораздо больше. Я настоятельно рекомендую проверить справку по curl и поэкспериментировать с ней.
А вы используете curl? И если да, то для чего?
Telegram-канал с полезностями и уютный чат
Curl stands for Client URL is a popular command-line tool used for transferring data from various sources using URL syntax. It supports a wide range of protocols like HTTP, HTTPS, and FTP making it a versatile tool for developers and system administrators. It is also used for transferring data using various network protocols. It is a powerful utility for developers to test APIs, upload or download files, and more.
Install Curl Windows is a straightforward process and in the following article, we will cover how to do so.
Prerequisites
Before proceeding with the installation of Curl on Windows ensure the following prerequisites:
- Windows 7 or later.
- Administrative privileges to execute the installation.
Using CURL on Our Windows 10 VPS!
Experience the ease and speed of Windows 10 VPS with pre-installed Curl. Enjoy blazing-fast SSD NVME speeds without any interruptions.
Installing the Curl command on Windows
Following are the methods for installing the Curl command in Windows older or later versions:
Method 1: Manual Installation
Download the Curl executable file by navigating to the official Curl download page. Download the appropriate version for your system and look for Win64 or Win32 zip files.
Once downloaded, extract the ZIP file to your preferred location for example C:\Curl location.
Add Curl to Windows PATH
This step allows you to run curl commands from any directory in your command prompt.
- Search for System Properties in the Start menu.
- In the System Properties window, click on Environment Variables.
- Under System Variables, find and select the Path variable, then click on Edit.
- Click on New and add the path to your Curl installation for example
C:\Curl\bin.
Click OK to close each window. Now verify the installation by typing the following command in your Windows Command Prompt.
curl --version
If installed correctly, it should display the version number.
Method 2: Using the Windows 10/11 Command Line
Windows 10 and later comes with Curl pre-installed. To check if Curl is already installed on your system:
- Open the Start menu.
- Type
cmdand open Command Prompt. - In the Command Prompt window, type
curl --versionand press Enter. - If Curl is installed, it will display the version number.
Method 3: Using a Chocolatey Package Manager
If you prefer using a package manager on Windows like Chocolatey then open Command Prompt as administrator. Paste the following command and execute it:
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
Wait for Chocolatey to install. In the same Command Prompt window, type the following:
choco install curl
Chocolatey will download and install Curl. After installation completes verify that in Command Prompt to check if it’s installed correctly.
Using Curl Command
Curl Windows cmd offers a vast array of options and functionalities. Here’s a basic example to get you started:
curl https://www.example.com
This command retrieves the content of the website and displays it in your command prompt window.
You can also download a file from a URL with the help of the Curl command:
curl https://example.com/file.txt -o filename.txt
This retrieves the file file.txt from https://example.com and saves it locally as filename.txt. Downloading silently without a progress meter.
curl -s https://example.com/file.txt -o filename.txt
Conclusion
Whether through manual downloading or using Chocolatey installing Curl on Windows is simple and enhances your ability to interact with web services right from your command line. Remember to always download software from official sources or trusted package managers to ensure security.
While installing Curl on Windows is possible, it might not be ideal for server-side tasks due to limitations in the Windows environment. Upgrading to an Ultahost VDS hosting plan offers a more robust solution. With root access on your VDS, you can effortlessly install Curl and leverage its functionalities for server-side automation tasks or data transfers.
FAQ
What is Curl on Windows?
Curl is a command-line tool used to transfer data from or to a server. It’s handy for fetching files, making requests, and more.
Why do I need to install Curl on Windows?
Installing Curl on Windows enables you to perform various tasks like downloading files, testing APIs, and accessing web services directly from your command prompt.
Is Curl free to use on Windows?
Yes, Curl is open-source software, meaning it’s free to download, install, and use on Windows operating systems.
How can I install Curl on Windows?
You can install Curl on Windows by downloading the installer from the official Curl website or by using package managers like Chocolatey.
cURL (short for «Client for URLs») is a command-line tool that empowers users to transfer data to or from a server using various protocols, such as HTTP, HTTPS, FTP, and more. It’s widely used by developers and system administrators worldwide due to its versatility and ease of use. In this article, we will delve deeply into how to install cURL on Windows 11, providing you with a comprehensive guide that covers various installation methods and common usage scenarios.
What is cURL?
Before we dive into the installation process, let’s take a moment to understand cURL and its significance. cURL is primarily known for its ability to work with APIs, automate processes, and create complex data transfer commands without needing a graphical user interface. Its rich feature set includes support for cookies, user authentication, proxy support, and much more. This makes it an essential tool for developers, especially when testing web applications or working in a development environment.
Checking if cURL is Already Installed
Windows 11 comes with the Windows Subsystem for Linux (WSL) and may have cURL pre-installed. To check if cURL is available on your Windows 11 system, follow these steps:
-
Open Command Prompt:
- Press
Win + R, typecmd, and hitEnterto open the Command Prompt.
- Press
-
Check cURL Version:
- Type the following command and press
Enter:curl --version - If cURL is installed, you will see version information. If it’s not installed, you will see an error message.
- Type the following command and press
Installing cURL on Windows 11
If cURL is not available on your system, you can easily install it using one of several methods. Here, we’ll explore various ways to install cURL, including using Windows Package Manager (winget), Chocolatey, and manual installation.
Method 1: Installing cURL Using Windows Package Manager (winget)
Windows 11 comes with a built-in package manager called winget, which allows you to install software easily. Here’s how to install cURL using winget:
-
Open Command Prompt as Administrator:
- Press
Win + Xand select “Windows Terminal (Admin)” or find «Command Prompt» in the start menu, right-click, and choose “Run as Administrator.”
- Press
-
Run the Installation Command:
- Type the following command and press
Enter:winget install curl - The package manager will fetch and install cURL swiftly. Once completed, you’ll receive a confirmation message.
- Type the following command and press
-
Verify Installation:
- Check if cURL is installed correctly by typing:
curl --version - Ensure you see the version details confirming a successful installation.
- Check if cURL is installed correctly by typing:
Method 2: Installing cURL Using Chocolatey
Chocolatey is another popular package manager for Windows that simplifies software installation. Follow these steps to install cURL via Chocolatey:
-
Install Chocolatey:
- If you haven’t installed Chocolatey yet, open PowerShell as Administrator. Run the following command:
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
- If you haven’t installed Chocolatey yet, open PowerShell as Administrator. Run the following command:
-
Install cURL:
- Once Chocolatey is installed, type the following command in the same PowerShell window:
choco install curl - Chocolatey will then handle the installation. Follow any on-screen prompts that may appear.
- Once Chocolatey is installed, type the following command in the same PowerShell window:
-
Verify Installation:
- After installation, you can confirm cURL’s installation by running:
curl --version
- After installation, you can confirm cURL’s installation by running:
Method 3: Manual Installation of cURL
If you prefer to install cURL manually, follow the steps outlined below:
-
Download cURL:
- Go to the official cURL website: https://curl.se/download.html.
- Scroll down to the «Windows» section and look for «curl for Windows». You’ll see multiple options available, including:
- Precompiled binaries for Win64/Win32.
- cURL with OpenSSL support or other SSL backends.
-
Choose the Appropriate Version:
- Download the appropriate ZIP file based on your system architecture (64-bit or 32-bit). For most users, the 64-bit version is recommended.
-
Extract the ZIP File:
- Locate the downloaded ZIP file (usually in your Downloads folder) and extract it using built-in Windows extraction or third-party software like WinRAR or 7-Zip.
-
Move cURL Files:
- After extraction, you will see multiple files and a folder named
curl. To make cURL easily accessible from the command line, it’s common practice to move the entire extracted directory to a dedicated location, such as:C:Program Filescurl
- After extraction, you will see multiple files and a folder named
-
Update System Path:
- You must add the cURL folder to your system’s
PATHenvironment variable:- Press
Win + Sand type “Environment Variables”, then select “Edit the system environment variables.” - Click the “Environment Variables” button.
- In the “System variables” section, find the
Pathvariable and select it. Click on “Edit.” - Click “New” and add the path where you extracted cURL (e.g.,
C:Program Filescurl). Press “OK” to close all dialogs.
- Press
- You must add the cURL folder to your system’s
-
Open Command Prompt:
- Open Command Prompt again and verify the installation by running:
curl --version
- Open Command Prompt again and verify the installation by running:
Using cURL on Windows 11
Now that you have cURL installed on Windows 11, let’s explore some of its essential features and usage examples.
Basic cURL Commands
-
Fetching a Web Page:
- To fetch the content of a webpage, use:
curl http://example.com - This command will display the HTML content of the specified URL in your terminal.
- To fetch the content of a webpage, use:
-
Saving Output to a File:
- You can save the output of a cURL command to a file using the
-ooption:curl -o mypage.html http://example.com - This command downloads the webpage and saves it as
mypage.html.
- You can save the output of a cURL command to a file using the
-
Basic Authentication:
- If a website requires authentication, you can pass your username and password using the
-uoption:curl -u username:password http://example.com
- If a website requires authentication, you can pass your username and password using the
-
Sending Data with POST Requests:
- To send data to a server using POST, use the
-doption:curl -X POST -d "param1=value1¶m2=value2" http://example.com/api - This command sends the specified parameters to the web API.
- To send data to a server using POST, use the
-
Setting Request Headers:
- Sometimes, you may need to customize request headers. Use the
-Hoption to set headers:curl -H "Authorization: Bearer your_token" http://example.com/api
- Sometimes, you may need to customize request headers. Use the
More Advanced Features
-
Using Cookies:
- You can send and receive cookies using cURL. To send cookies:
curl -b "name=value" http://example.com - To store cookies received during a session:
curl -c cookies.txt http://example.com
- You can send and receive cookies using cURL. To send cookies:
-
Downloading Files:
- cURL is great for downloading files from the web:
curl -O http://example.com/file.zip - The
-Ooption saves the file with the same name as on the server.
- cURL is great for downloading files from the web:
-
Rate Limiting:
- To avoid being rate-limited by a server, you can introduce a delay between requests:
curl --limit-rate 100K http://example.com
- To avoid being rate-limited by a server, you can introduce a delay between requests:
Troubleshooting Common cURL Issues
While cURL is generally reliable, users may encounter issues. Here are some common problems and potential solutions:
-
cURL Command Not Found:
- If you receive a «command not found» error, ensure that cURL is installed and that your system path is configured correctly.
-
SSL Certificate Issues:
- If you face SSL certificate problems while accessing HTTPS URLs, try:
curl -k https://example.com - The
-koption allows cURL to bypass SSL certificate verification (not recommended for production).
- If you face SSL certificate problems while accessing HTTPS URLs, try:
-
Connection Timeout:
- If cURL times out, you can adjust the timeout settings:
curl --connect-timeout 30 http://example.com - This increases the connection timeout to 30 seconds.
- If cURL times out, you can adjust the timeout settings:
-
Verbose Mode:
- To debug issues with cURL commands, enable verbose mode to see detailed logs:
curl -v http://example.com
- To debug issues with cURL commands, enable verbose mode to see detailed logs:
Conclusion
Installing and using cURL on Windows 11 is a straightforward process that enhances your command-line capabilities significantly. From accessing and interacting with APIs to downloading files and automating various web tasks, cURL is an indispensable tool for developers and system administrators.
By following the methods in this guide, you should now have a functional installation of cURL on your Windows 11 system. Experiment with various commands and features to unlock the full potential of this versatile tool.
As you progress in your development or administrative tasks, understanding cURL will only add to your arsenal, making your workflow smoother and more efficient. Happy cURLing!
Download the latest zipped binary
You can download it at https://curl.se/windows/, choose either 64-bit or 32-bit, depends on your machine preference.
Extract and Move to Program Files Directory
Program Files directory is a good place for any program directory, so let’s create a folder inside C:\Program Files named Curl and extract the zip to this folder.
Add Path For Executable Curl
Hit the Windows icon on the keyboard and type edit the system environment variables and the menu. The System Properties window will popped-up. Click the environment variables button and the environment variables window will popped-up. In the User variables for <your-user>, find and choose Path and then hit the Edit button. The Edit environment variable window will popped-up and click the New button and add C:\Program Files\Curl\bin and then hit OK for all windows.
Test the Curl
Open new CMD/CommandPrompt instance and try to type curl --help and enter. If you see the list of commands usage, then it already works.
C:\Users\dendi>curl --help
Usage: curl [options...] <url>
--abstract-unix-socket <path> Connect via abstract Unix domain socket
--anyauth Pick any authentication method
-a, --append Append to target file when uploading
--basic Use HTTP Basic Authentication
--cacert <CA certificate> CA certificate to verify peer against
--capath <dir> CA directory to verify peer against
-E, --cert <certificate[:password]> Client certificate file and password
...
Enter fullscreen mode
Exit fullscreen mode
Hit an Open API
try it like this:
curl -X GET "https://swapi.dev/api/people"
Enter fullscreen mode
Exit fullscreen mode
See it it succeed retrieving the data
cURL (Client URL) — это инструмент командной строки и библиотека для передачи данных с серверов и на серверы по различным протоколам. Использование cURL API примеров в документации может значительно ускорить процесс разработки и тестирования.
Несколько причин ускорения:
- Наглядность и простота: Примеры показывают конкретные команды и параметры, которые нужно использовать, что упрощает понимание и применение API.
- Быстрое тестирование: С cURL можно сразу проверить работу API, не разрабатывая сложные клиентские приложения.
- Легкость интеграции: cURL команды можно легко интегрировать в скрипты, что позволяет автоматизировать процессы взаимодействия с API.
- Отладка и диагностика: Легко увидеть запросы и ответы, что помогает быстро находить и исправлять ошибки.
- Кроссплатформенность: cURL работает на разных операционных системах, что позволяет использовать его в любом окружении.
Часто примеры из API используют bash синтаксис и переменные. Поэтому в данной статье рассматриваем установку cURL по Windows вместе с интерпретатором bash.
Установка вместе с git
Установка MinGW (Minimalist GNU for Windows) вместе с Git на Windows предоставляет несколько преимуществ, особенно для разработчиков, работающих с Git и другими инструментами командной строки. Вот некоторые из основных преимуществ:
- Git Bash: При установке Git для Windows с MinGW вы получаете Git Bash — эмулятор командной строки Unix для Windows. Это позволяет использовать множество команд Unix/Linux прямо в Windows, что значительно упрощает работу для разработчиков, привыкших к этим системам.
- Наличие стандартных утилит Unix: MinGW включает множество утилит и инструментов, таких как curl, ssh, scp, rsync, vim, nano, grep, awk, sed, и многие другие. Это делает Git Bash мощным инструментом для разработчиков.
- Простота установки и настройки: Установщик Git для Windows предлагает опцию установки Git Bash и MinGW в несколько кликов, что делает процесс установки быстрым и простым.
Чтобы установить Git с MinGW на Windows, выполните следующие шаги:
- Скачайте установщик Git для Windows с официального сайта: https://git-scm.com/download/win
- Запустите установщик и следуйте инструкциям.
- Выберите Git from the command line and also from 3rd-party software, как и рекомендуется установщиком.
- Запускаем Git Bash и проверяем версию cURL.
curl --version
Использование cURL c API RUVDS
API RUVDS позволяет автоматизировать управление виртуальными серверами сервиса ruvds.com. Документация к API расположена по адресу https://ruvds.com/api-docs/.
Все точки доступа снабжены примерами cURL API. Например, получение баланса https://ruvds.com/api-docs/#tag/Balance/operation/balance_get.
RUVDS_TOKEN='Token from https://ruvds.com/my/settings/api'
API_URL='https://api.ruvds.com'
curl -X GET \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $RUVDS_TOKEN" \
"$API_URL/v2/balance"
Для получения токена доступа к API RUVDS:
- Заходим в личный кабинет по адресу https://ruvds.com.
- Переходим в Настройки -> Информация API.
- Нажимаем на кнопку Создать токен.
- Сохраняем токен в надёжном месте. ВАЖНО: в целях безопасности токен показывается только один раз. В случае утери токен, нужно сгенерировать его снова.
Теперь мы готовы выполнить пример из cURL API RUVDS. Пример результата на скриншоте ниже.
