Как установить curl на windows 10

Curl (client URL) — это инструмент командной строки на основе библиотеки libcurl для передачи данных с сервера и на сервер при помощи различных протоколов, в то...

Время прочтения
9 мин

Просмотры 22K

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

Silently download a file and save with a custom name using curl

Скачивание файла без индикатора и сохранение под произвольным именем

▍ Продолжение прерванного скачивания

Наличие 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:UsersSurenderDownloadssample1.zip -u testlabsurender ftps://192.168.0.80/awesomewebsite.com/files/

Выгрузка файла на удалённый сервер

Опция -k добавляется для устранения проблем с сертификатами на случай, если веб-сервер использует самоподписанный сертификат. Наклонная черта в конце URL сообщает curl, что конечная точка является папкой. Можно указать несколько имён файлов, например «{sample1.zip,sample2.zip}». Ниже показано, как с помощью одной команды curl можно выгрузить на сервер несколько файлов:

curl -kT sample[1-5].zip -u testlabsurender ftps://192.168.0.80/awesomewebsite.com/files/

Выгрузка нескольких файлов на сервер

▍ Последовательность команд

Как говорилось ранее, curl поддерживает различные методы в зависимости от используемого протокола. Дополнительные команды можно отправлять при помощи —quote (или -Q) для выполнения операции до или после обычной операции curl. Например, можно скачать файл с удалённого сервера по протоколу FTPS и удалить файл с сервера после успешного скачивания. Для этого нужно выполнить следующую команду:

curl -u testlabsurender -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-канал с полезностями и уютный чат

how to install curl and libcurl

Installing Binary Packages

Lots of people download binary distributions of curl and libcurl. This
document does not describe how to install curl or libcurl using such a binary
package. This document describes how to compile, build and install curl and
libcurl from source code.

Building using vcpkg

You can download and install curl and libcurl using the vcpkg dependency manager:

git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.sh
./vcpkg integrate install
vcpkg install curl[tool]

The curl port in vcpkg is kept up to date by Microsoft team members and
community contributors. If the version is out of date, please create an issue
or pull request on the vcpkg repository.

Building from git

If you get your code off a git repository instead of a release tarball, see
the GIT-INFO file in the root directory for specific instructions on how to
proceed.

Unix

A normal Unix installation is made in three or four steps (after you have
unpacked the source archive):

./configure --with-openssl [--with-gnutls --with-wolfssl]
make
make test (optional)
make install

(Adjust the configure line accordingly to use the TLS library you want.)

You probably need to be root when doing the last command.

Get a full listing of all available configure options by invoking it like:

If you want to install curl in a different file hierarchy than /usr/local,
specify that when running configure:

./configure --prefix=/path/to/curl/tree

If you have write permission in that directory, you can do ‘make install’
without being root. An example of this would be to make a local install in
your own home directory:

./configure --prefix=$HOME
make
make install

The configure script always tries to find a working SSL library unless
explicitly told not to. If you have OpenSSL installed in the default search
path for your compiler/linker, you do not need to do anything special. If you
have OpenSSL installed in /usr/local/ssl, you can run configure like:

./configure --with-openssl

If you have OpenSSL installed somewhere else (for example, /opt/OpenSSL) and
you have pkg-config installed, set the pkg-config path first, like this:

env PKG_CONFIG_PATH=/opt/OpenSSL/lib/pkgconfig ./configure --with-openssl

Without pkg-config installed, use this:

./configure --with-openssl=/opt/OpenSSL

If you insist on forcing a build without SSL support, you can run configure
like this:

./configure --without-ssl

If you have OpenSSL installed, but with the libraries in one place and the
header files somewhere else, you have to set the LDFLAGS and CPPFLAGS
environment variables prior to running configure. Something like this should
work:

CPPFLAGS="-I/path/to/ssl/include" LDFLAGS="-L/path/to/ssl/lib" ./configure

If you have shared SSL libs installed in a directory where your runtime
linker does not find them (which usually causes configure failures), you can
provide this option to gcc to set a hard-coded path to the runtime linker:

LDFLAGS=-Wl,-R/usr/local/ssl/lib ./configure --with-openssl

Static builds

To force a static library compile, disable the shared library creation by
running configure like:

./configure --disable-shared

The configure script is primarily done to work with shared/dynamic third party
dependencies. When linking with shared libraries, the dependency «chain» is
handled automatically by the library loader — on all modern systems.

If you instead link with a static library, you need to provide all the
dependency libraries already at the link command line.

Figuring out all the dependency libraries for a given library is hard, as it
might involve figuring out the dependencies of the dependencies and they vary
between platforms and change between versions.

When using static dependencies, the build scripts will mostly assume that you,
the user, will provide all the necessary additional dependency libraries as
additional arguments in the build. With configure, by setting LIBS or
LDFLAGS on the command line.

Building statically is not for the faint of heart.

Debug

If you are a curl developer and use gcc, you might want to enable more debug
options with the --enable-debug option.

curl can be built to use a whole range of libraries to provide various useful
services, and configure will try to auto-detect a decent default. But if you
want to alter it, you can select how to deal with each individual library.

Select TLS backend

These options are provided to select the TLS backend to use.

  • AmiSSL: --with-amissl
  • BearSSL: --with-bearssl
  • GnuTLS: --with-gnutls.
  • mbedTLS: --with-mbedtls
  • NSS: --with-nss
  • OpenSSL: --with-openssl (also for BoringSSL, libressl and quictls)
  • rustls: --with-rustls
  • Schannel: --with-schannel
  • Secure Transport: --with-secure-transport
  • wolfSSL: --with-wolfssl

You can build curl with multiple TLS backends at your choice, but some TLS
backends cannot be combined: if you build with an OpenSSL fork (or wolfSSL),
you cannot add another OpenSSL fork (or wolfSSL) simply because they have
conflicting identical symbol names.

When you build with multiple TLS backends, you can select the active one at
run-time when curl starts up.

Windows

Building Windows DLLs and C runtime (CRT) linkage issues

As a general rule, building a DLL with static CRT linkage is highly
discouraged, and intermixing CRTs in the same app is something to avoid at
any cost.

Reading and comprehending Microsoft Knowledge Base articles KB94248 and
KB140584 is a must for any Windows developer. Especially important is full
understanding if you are not going to follow the advice given above.

  • How To Use the C Run-Time
  • Run-Time Library Compiler Options
  • Potential Errors Passing CRT Objects Across DLL Boundaries

If your app is misbehaving in some strange way, or it is suffering from memory
corruption, before asking for further help, please try first to rebuild every
single library your app uses as well as your app using the debug
multi-threaded dynamic C runtime.

If you get linkage errors read section 5.7 of the FAQ document.

MinGW32

Make sure that MinGW32’s bin directory is in the search path, for example:

set PATH=c:mingw32bin;%PATH%

then run mingw32-make mingw32 in the root dir. There are other
make targets available to build libcurl with more features, use:

  • mingw32-make mingw32-zlib to build with Zlib support;
  • mingw32-make mingw32-ssl-zlib to build with SSL and Zlib enabled;
  • mingw32-make mingw32-ssh2-ssl-zlib to build with SSH2, SSL, Zlib;
  • mingw32-make mingw32-ssh2-ssl-sspi-zlib to build with SSH2, SSL, Zlib
    and SSPI support.

If you have any problems linking libraries or finding header files, be sure
to verify that the provided Makefile.mk files use the proper paths, and
adjust as necessary. It is also possible to override these paths with
environment variables, for example:

set ZLIB_PATH=c:zlib-1.2.12
set OPENSSL_PATH=c:openssl-3.0.5
set LIBSSH2_PATH=c:libssh2-1.10.0

It is also possible to build with other LDAP installations than MS LDAP;
currently it is possible to build with native Win32 OpenLDAP, or with the
Novell CLDAP SDK. If you want to use these you need to set these vars:

set CPPFLAGS=-Ic:/openldap/include -DCURL_HAS_OPENLDAP_LDAPSDK
set LDFLAGS=-Lc:/openldap/lib
set LIBS=-lldap -llber

or for using the Novell SDK:

set CPPFLAGS=-Ic:/openldapsdk/inc -DCURL_HAS_NOVELL_LDAPSDK
set LDFLAGS=-Lc:/openldapsdk/lib/mscvc
set LIBS=-lldapsdk -lldapssl -lldapx

If you want to enable LDAPS support then append -ldaps to the make target.

Cygwin

Almost identical to the Unix installation. Run the configure script in the
curl source tree root with sh configure. Make sure you have the sh
executable in /bin/ or you will see the configure fail toward the end.

Run make

MS-DOS

Requires DJGPP in the search path and pointing to the Watt-32 stack via
WATT_PATH=c:/djgpp/net/watt.

Run make -f Makefile.dist djgpp in the root curl dir.

For build configuration options, please see the MinGW32 section.

Notes:

  • DJGPP 2.04 beta has a sscanf() bug so the URL parsing is not done
    properly. Use DJGPP 2.03 until they fix it.

  • Compile Watt-32 (and OpenSSL) with the same version of DJGPP. Otherwise
    things go wrong because things like FS-extensions and errno values have
    been changed between releases.

AmigaOS

Run make -f Makefile.dist amiga in the root curl dir.

For build configuration options, please see the MinGW32 section.

Disabling Specific Protocols in Windows builds

The configure utility, unfortunately, is not available for the Windows
environment, therefore, you cannot use the various disable-protocol options of
the configure utility on this platform.

You can use specific defines to disable specific protocols and features. See
CURL-DISABLE for the full list.

If you want to set any of these defines you have the following options:

  • Modify lib/config-win32.h
  • Modify lib/curl_setup.h
  • Modify winbuild/Makefile.vc
  • Modify the «Preprocessor Definitions» in the libcurl project

Note: The pre-processor settings can be found using the Visual Studio IDE
under «Project -> Properties -> Configuration Properties -> C/C++ ->
Preprocessor».

Using BSD-style lwIP instead of Winsock TCP/IP stack in Win32 builds

In order to compile libcurl and curl using BSD-style lwIP TCP/IP stack it is
necessary to make the definition of the preprocessor symbol USE_LWIPSOCK
visible to libcurl and curl compilation processes. To set this definition you
have the following alternatives:

  • Modify lib/config-win32.h and src/config-win32.h
  • Modify winbuild/Makefile.vc
  • Modify the «Preprocessor Definitions» in the libcurl project

Note: The pre-processor settings can be found using the Visual Studio IDE
under «Project -> Properties -> Configuration Properties -> C/C++ ->
Preprocessor».

Once that libcurl has been built with BSD-style lwIP TCP/IP stack support, in
order to use it with your program it is mandatory that your program includes
lwIP header file <lwip/opt.h> (or another lwIP header that includes this)
before including any libcurl header. Your program does not need the
USE_LWIPSOCK preprocessor definition which is for libcurl internals only.

Compilation has been verified with lwIP 1.4.0.

This BSD-style lwIP TCP/IP stack support must be considered experimental given
that it has been verified that lwIP 1.4.0 still needs some polish, and libcurl
might yet need some additional adjustment.

Important static libcurl usage note

When building an application that uses the static libcurl library on Windows,
you must add -DCURL_STATICLIB to your CFLAGS. Otherwise the linker will
look for dynamic import symbols.

Legacy Windows and SSL

Schannel (from Windows SSPI), is the native SSL library in Windows. However,
Schannel in Windows <= XP is unable to connect to servers that
no longer support the legacy handshakes and algorithms used by those
versions. If you will be using curl in one of those earlier versions of
Windows you should choose another SSL backend such as OpenSSL.

Apple Platforms (macOS, iOS, tvOS, watchOS, and their simulator counterparts)

On modern Apple operating systems, curl can be built to use Apple’s SSL/TLS
implementation, Secure Transport, instead of OpenSSL. To build with Secure
Transport for SSL/TLS, use the configure option --with-secure-transport.

When Secure Transport is in use, the curl options --cacert and --capath
and their libcurl equivalents, will be ignored, because Secure Transport uses
the certificates stored in the Keychain to evaluate whether or not to trust
the server. This, of course, includes the root certificates that ship with the
OS. The --cert and --engine options, and their libcurl equivalents, are
currently unimplemented in curl with Secure Transport.

In general, a curl build for an Apple ARCH/SDK/DEPLOYMENT_TARGET combination
can be taken by providing appropriate values for ARCH, SDK, DEPLOYMENT_TARGET
below and running the commands:

# Set these three according to your needs
export ARCH=x86_64
export SDK=macosx
export DEPLOYMENT_TARGET=10.8

export CFLAGS="-arch $ARCH -isysroot $(xcrun -sdk $SDK --show-sdk-path) -m$SDK-version-min=$DEPLOYMENT_TARGET"
./configure --host=$ARCH-apple-darwin --prefix $(pwd)/artifacts --with-secure-transport
make -j8
make install

Above will build curl for macOS platform with x86_64 architecture and 10.8 as deployment target.

Here is an example for iOS device:

export ARCH=arm64
export SDK=iphoneos
export DEPLOYMENT_TARGET=11.0

export CFLAGS="-arch $ARCH -isysroot $(xcrun -sdk $SDK --show-sdk-path) -m$SDK-version-min=$DEPLOYMENT_TARGET"
./configure --host=$ARCH-apple-darwin --prefix $(pwd)/artifacts --with-secure-transport
make -j8
make install

Another example for watchOS simulator for macs with Apple Silicon:

export ARCH=arm64
export SDK=watchsimulator
export DEPLOYMENT_TARGET=5.0

export CFLAGS="-arch $ARCH -isysroot $(xcrun -sdk $SDK --show-sdk-path) -m$SDK-version-min=$DEPLOYMENT_TARGET"
./configure --host=$ARCH-apple-darwin --prefix $(pwd)/artifacts --with-secure-transport
make -j8
make install

In all above, the built libraries and executables can be found in the
artifacts folder.

Android

When building curl for Android it’s recommended to use a Linux/macOS environment
since using curl’s configure script is the easiest way to build curl
for Android. Before you can build curl for Android, you need to install the
Android NDK first. This can be done using the SDK Manager that is part of
Android Studio. Once you have installed the Android NDK, you need to figure out
where it has been installed and then set up some environment variables before
launching configure. On macOS, those variables could look like this to compile
for aarch64 and API level 29:

export ANDROID_NDK_HOME=~/Library/Android/sdk/ndk/25.1.8937393 # Point into your NDK.
export HOST_TAG=darwin-x86_64 # Same tag for Apple Silicon. Other OS values here: https://developer.android.com/ndk/guides/other_build_systems#overview
export TOOLCHAIN=$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/$HOST_TAG
export AR=$TOOLCHAIN/bin/llvm-ar
export AS=$TOOLCHAIN/bin/llvm-as
export CC=$TOOLCHAIN/bin/aarch64-linux-android21-clang
export CXX=$TOOLCHAIN/bin/aarch64-linux-android21-clang++
export LD=$TOOLCHAIN/bin/ld
export RANLIB=$TOOLCHAIN/bin/llvm-ranlib
export STRIP=$TOOLCHAIN/bin/llvm-strip

When building on Linux or targeting other API levels or architectures, you need
to adjust those variables accordingly. After that you can build curl like this:

./configure --host aarch64-linux-android --with-pic --disable-shared

Note that this will not give you SSL/TLS support. If you need SSL/TLS, you have
to build curl against a SSL/TLS layer, e.g. OpenSSL, because it’s impossible for
curl to access Android’s native SSL/TLS layer. To build curl for Android using
OpenSSL, follow the OpenSSL build instructions and then install libssl.a and
libcrypto.a to $TOOLCHAIN/sysroot/usr/lib and copy include/openssl to
$TOOLCHAIN/sysroot/usr/include. Now you can build curl for Android using
OpenSSL like this:

LIBS="-lssl -lcrypto -lc++" # For OpenSSL/BoringSSL. In general, you'll need to the SSL/TLS layer's transtive dependencies if you're linking statically.
./configure --host aarch64-linux-android --with-pic --disable-shared --with-openssl="$TOOLCHAIN/sysroot/usr"

IBM i

For IBM i (formerly OS/400), you can use curl in two different ways:

  • Natively, running in the ILE. The obvious use is being able to call curl
    from ILE C or RPG applications.

    • You will need to build this from source. See packages/OS400/README for
      the ILE specific build instructions.
  • In the PASE environment, which runs AIX programs. curl will be built as
    it would be on AIX.

    • IBM provides builds of curl in their Yum repository for PASE software.
    • To build from source, follow the Unix instructions.

There are some additional limitations and quirks with curl on this platform;
they affect both environments.

Multi-threading notes

By default, jobs in IBM i will not start with threading enabled. (Exceptions
include interactive PASE sessions started by QP2TERM or SSH.) If you use
curl in an environment without threading when options like asynchronous DNS
were enabled, you will get messages like:

getaddrinfo() thread failed to start

Do not panic. curl and your program are not broken. You can fix this by:

  • Set the environment variable QIBM_MULTI_THREADED to Y before starting
    your program. This can be done at whatever scope you feel is appropriate.
  • Alternatively, start the job with the ALWMLTTHD parameter set to *YES.

Cross compile

Download and unpack the curl package.

cd to the new directory. (e.g. cd curl-7.12.3)

Set environment variables to point to the cross-compile toolchain and call
configure with any options you need. Be sure and specify the --host and
--build parameters at configuration time. The following script is an example
of cross-compiling for the IBM 405GP PowerPC processor using the toolchain on
Linux.

#! /bin/sh

export PATH=$PATH:/opt/hardhat/devkit/ppc/405/bin
export CPPFLAGS="-I/opt/hardhat/devkit/ppc/405/target/usr/include"
export AR=ppc_405-ar
export AS=ppc_405-as
export LD=ppc_405-ld
export RANLIB=ppc_405-ranlib
export CC=ppc_405-gcc
export NM=ppc_405-nm

./configure --target=powerpc-hardhat-linux
    --host=powerpc-hardhat-linux
    --build=i586-pc-linux-gnu
    --prefix=/opt/hardhat/devkit/ppc/405/target/usr/local
    --exec-prefix=/usr/local

You may also need to provide a parameter like --with-random=/dev/urandom to
configure as it cannot detect the presence of a random number generating
device for a target system. The --prefix parameter specifies where curl
will be installed. If configure completes successfully, do make and make install as usual.

In some cases, you may be able to simplify the above commands to as little as:

./configure --host=ARCH-OS

REDUCING SIZE

There are a number of configure options that can be used to reduce the size of
libcurl for embedded applications where binary size is an important factor.
First, be sure to set the CFLAGS variable when configuring with any relevant
compiler optimization flags to reduce the size of the binary. For gcc, this
would mean at minimum the -Os option, and potentially the -march=X,
-mdynamic-no-pic and -flto options as well, e.g.

./configure CFLAGS='-Os' LDFLAGS='-Wl,-Bsymbolic'...

Note that newer compilers often produce smaller code than older versions
due to improved optimization.

Be sure to specify as many --disable- and --without- flags on the
configure command-line as you can to disable all the libcurl features that you
know your application is not going to need. Besides specifying the
--disable-PROTOCOL flags for all the types of URLs your application will not
use, here are some other flags that can reduce the size of the library by
disabling support for some feature:

  • --disable-alt-svc (HTTP Alt-Svc)
  • --disable-ares (the C-ARES DNS library)
  • --disable-cookies (HTTP cookies)
  • --disable-crypto-auth (cryptographic authentication)
  • --disable-dateparse (date parsing for time conditionals)
  • --disable-dnsshuffle (internal server load spreading)
  • --disable-doh (DNS-over-HTTP)
  • --disable-get-easy-options (lookup easy options at runtime)
  • --disable-hsts (HTTP Strict Transport Security)
  • --disable-http-auth (all HTTP authentication)
  • --disable-ipv6 (IPv6)
  • --disable-libcurl-option (—libcurl C code generation support)
  • --disable-manual (built-in documentation)
  • --disable-netrc (.netrc file)
  • --disable-ntlm-wb (NTLM WinBind)
  • --disable-progress-meter (graphical progress meter in library)
  • --disable-proxy (HTTP and SOCKS proxies)
  • --disable-pthreads (multi-threading)
  • --disable-socketpair (socketpair for asynchronous name resolving)
  • --disable-threaded-resolver (threaded name resolver)
  • --disable-tls-srp (Secure Remote Password authentication for TLS)
  • --disable-unix-sockets (UNIX sockets)
  • --disable-verbose (eliminates debugging strings and error code strings)
  • --disable-versioned-symbols (versioned symbols)
  • --enable-symbol-hiding (eliminates unneeded symbols in the shared library)
  • --without-brotli (Brotli on-the-fly decompression)
  • --without-libpsl (Public Suffix List in cookies)
  • --without-nghttp2 (HTTP/2 using nghttp2)
  • --without-ngtcp2 (HTTP/2 using ngtcp2)
  • --without-zstd (Zstd on-the-fly decompression)
  • --without-libidn2 (internationalized domain names)
  • --without-librtmp (RTMP)
  • --without-ssl (SSL/TLS)
  • --without-zlib (on-the-fly decompression)

The GNU compiler and linker have a number of options that can reduce the
size of the libcurl dynamic libraries on some platforms even further.
Specify them by providing appropriate CFLAGS and LDFLAGS variables on
the configure command-line, e.g.

CFLAGS="-Os -ffunction-sections -fdata-sections
        -fno-unwind-tables -fno-asynchronous-unwind-tables -flto"
LDFLAGS="-Wl,-s -Wl,-Bsymbolic -Wl,--gc-sections"

Be sure also to strip debugging symbols from your binaries after compiling
using ‘strip’ (or the appropriate variant if cross-compiling). If space is
really tight, you may be able to remove some unneeded sections of the shared
library using the -R option to objcopy (e.g. the .comment section).

Using these techniques it is possible to create a basic HTTP-only libcurl
shared library for i386 Linux platforms that is only 133 KiB in size
(as of libcurl version 7.80.0, using gcc 11.2.0).

You may find that statically linking libcurl to your application will result
in a lower total size than dynamically linking.

Note that the curl test harness can detect the use of some, but not all, of
the --disable statements suggested above. Use will cause tests relying on
those features to fail. The test harness can be manually forced to skip the
relevant tests by specifying certain key words on the runtests.pl command
line. Following is a list of appropriate key words for those configure options
that are not automatically detected:

  • --disable-cookies !cookies
  • --disable-dateparse !RETRY-AFTER !CURLOPT_TIMECONDITION !CURLINFO_FILETIME !If-Modified-Since !curl_getdate !-z
  • --disable-libcurl-option !--libcurl
  • --disable-verbose !verbose logs

PORTS

This is a probably incomplete list of known CPU architectures and operating
systems that curl has been compiled for. If you know a system curl compiles
and runs on, that is not listed, please let us know!

92 Operating Systems

AIX, AmigaOS, Android, Aros, BeOS, Blackberry 10, Blackberry Tablet OS,
Cell OS, Chrome OS, Cisco IOS, Cygwin, DG/UX, Dragonfly BSD, DR DOS, eCOS,
FreeBSD, FreeDOS, FreeRTOS, Fuchsia, Garmin OS, Genode, Haiku, HardenedBSD,
HP-UX, Hurd, Illumos, Integrity, iOS, ipadOS, IRIX, Linux, Lua RTOS,
Mac OS 9, macOS, Mbed, Micrium, MINIX, MorphOS, MPE/iX, MS-DOS, NCR MP-RAS,
NetBSD, Netware, Nintendo Switch, NonStop OS, NuttX, Omni OS, OpenBSD,
OpenStep, Orbis OS, OS/2, OS/400, OS21, Plan 9, PlayStation Portable, QNX,
Qubes OS, ReactOS, Redox, RICS OS, RTEMS, Sailfish OS, SCO Unix, Serenity,
SINIX-Z, Solaris, SunOS, Syllable OS, Symbian, Tizen, TPF, Tru64, tvOS,
ucLinux, Ultrix, UNICOS, UnixWare, VMS, vxWorks, watchOS, WebOS,
Wii system software, Windows, Windows CE, Xbox System, Xenix, Zephyr,
z/OS, z/TPF, z/VM, z/VSE

26 CPU Architectures

Alpha, ARC, ARM, AVR32, CompactRISC, Elbrus, ETRAX, HP-PA, Itanium,
LoongArch, m68k, m88k, MicroBlaze, MIPS, Nios, OpenRISC, POWER, PowerPC,
RISC-V, s390, SH4, SPARC, Tilera, VAX, x86, Xtensa

Как установить CURL на Windows 10

cURL — кроссплатформенная служебная программа командной строки, позволяющая взаимодействовать с множеством различных серверов по множеству различных протоколов с синтаксисом URL. Она бесплатна и используется многими приложениями. В этой заметке я расскажу о том, как устанавливать CURL на Windows.

Начиная с Windows 10 v1803, операционная система уже поставляется с копией CURL. Она уже настроена и вы можете приступать к ее использованию прямо сейчас. Откройте командную строку и введите «curl -help«. Если ошибок нет, и отображаются все опции CURL, то она установлена на ваш Windows 10.

Как установить CURL на Windows 10 1

Наряду с Curl, Microsoft также запустила Tar, инструмент командной строки для извлечения файлов и создания архивов.

Если по каким-то причинам вы не нашли CURL, установленный на вашей ОС Windows, вот как его установить.

1. Загрузите и установите программу Curl с официального сайта

Перейдите сюда и загрузите версию, которая подходит для вашей системы (32 или 64 bit). Если вы хотите загрузить определенные пакеты, посетите страницу Пакеты CURL. Здесь вы можете скачать исполняемый файл curl, программу разработки libcurl, libcurl или исходный код. Не забудьте добавить исполняемый файл в свой каталог.

2. CURL для Windows

Если вы предпочитаете установщик в 1 щелчок, используйте cURL для Windows. Вы можете скачать его здесь.


Спасибо, что читаете! На данный момент большинство моих заметок, статей и подборок выходит в telegram канале «Левашов». Обязательно подписывайтесь, чтобы не пропустить новости мира ИТ, полезные инструкции и нужные сервисы.


Респект за пост! Спасибо за работу!

Хотите больше постов в блоге? Подборок софта и сервисов, а также обзоры на гаджеты? Сейчас, чтобы писать регулярно и радовать вас большими обзорами, мне требуется помощь. Чтобы поддерживать сайт на регулярной основе, вы можете оформить подписку на российском сервисе Boosty. Или воспользоваться ЮMoney (бывшие Яндекс Деньги) для разовой поддержки:


Заранее спасибо! Все собранные средства будут пущены на развитие сайта. Поддержка проекта является подарком владельцу сайта.


Download Article

An easy-to-follow guide on how to install cURL on your computer


Download Article

cURL is short for Client URL and is a command-line or script used to transfer data.[1]
This wikiHow will show you how to install cURL on Windows.

Steps

  1. Image titled Install Curl on Windows Step 1

    1

    Go to https://curl.haxx.se/download.html in a web browser. cURL is used in command lines or scripts to transfer data. For example curl https://www.wikihow.com will return the HTTP response.

  2. Image titled Install Curl on Windows Step 2

    2

    Click curl Download Wizard. You’ll see this under the «Download Wizard» header.

    Advertisement

  3. Image titled Install Curl on Windows Step 3

    3

    Click curl executable. This is usually the first listing in the menu.

  4. Image titled Install Curl on Windows Step 4

    4

    Click the drop-down under «Select Operating System» and select Windows 32 or 64. If your CPU is a 32-bit processor, you’ll need to download the 32-bit version; if your CPU is a 64-bit processor, you can download either, but the 64-bit version of cURL will take full advantage of your CPU’s benefits.[2]

  5. Image titled Install Curl on Windows Step 5

    5

    Click Select. This is next to the drop-down menu of available OS-compatible downloads.

  6. Image titled Install Curl on Windows Step 6

    6

    Select what version you want (only available for certain downloads, like Win32). Some builds of cURL, like with Win32, have different versions. Click the drop-down to select a version.

    • If «Generic» is available, choose that.
    • Click Select to continue. You’ll be directed to a page of recommended downloads.
  7. Image titled Install Curl on Windows Step 7

    7

    Click the arrow in the first result. This is usually a link to a download from the official cURL website.

  8. Image titled Install Curl on Windows Step 8

    8

    Click the build you want. You may have to choose between a 32-bit and 64-bit build again.

  9. Image titled Install Curl on Windows Step 9

    9

    Save the downloaded file. When your file browser pops up, choose a location to save the file and click Save.

  10. Image titled Install Curl on Windows Step 10

    10

    Extract the files from the zipped folder. A zipped file will download to the location you specified, and you’ll need to unzip the folder to continue.

    • Right-click on the folder and select ‘Extract All, then specify a location where you want to unzip the files to.
  11. Image titled Install Curl on Windows Step 11

    11

    Open the unzipped folder and files and find «curl.exe.«. You’ll find the root folder in the location you previously specified. And you’ll probably find «curl.exe» in the bin folder.

  12. Image titled Install Curl on Windows Step 12

    12

    Type «cmd» in the address bar of your file browser to launch a command window. You can also type «CMD» in the search area of the Start Menu.

  13. Image titled Install Curl on Windows Step 13

    13

    Type «curl» into the command window and press Enter. If you opened the command window from the address bar of file browser while you were navigated in the «bin» folder, command prompt should already have the appropriate address entered.

    • You should see command prompt return to you commands that you can try with curl.[3]
    • You can use the curl command on your computer from that specific path. If you type «curl» in command prompt at a path different from where it’s located (in the «bin» folder of the unzipped folder), it will not work.
  14. Advertisement

Ask a Question

200 characters left

Include your email address to get a message when this question is answered.

Submit

Advertisement

Thanks for submitting a tip for review!

References

About This Article

Article SummaryX

1. Go to https://curl.haxx.se/download.html in a web browser.

2. Click curl Download Wizard.

3. Click curl executable.
4. Click the drop-down under «Select Operating System» and select Windows 32 or 64.

5. Click Select.

6. Select what version you want (only available for certain downloads, like Win32).

7. Click the arrow in the first result.

8. Click the build you want.

9. Save the downloaded file.

10. Extract the files from the zipped folder.

11. Open the unzipped folder and files and find «curl.exe.»

12. Type «cmd» in the address bar of your file browser to launch a command window.

13. Type «curl» into the command window and press Enter.

Did this summary help you?

Thanks to all authors for creating a page that has been read 25,955 times.

Is this article up to date?


Download Article

An easy-to-follow guide on how to install cURL on your computer


Download Article

cURL is short for Client URL and is a command-line or script used to transfer data.[1]
This wikiHow will show you how to install cURL on Windows.

Steps

  1. Image titled Install Curl on Windows Step 1

    1

    Go to https://curl.haxx.se/download.html in a web browser. cURL is used in command lines or scripts to transfer data. For example curl https://www.wikihow.com will return the HTTP response.

  2. Image titled Install Curl on Windows Step 2

    2

    Click curl Download Wizard. You’ll see this under the «Download Wizard» header.

    Advertisement

  3. Image titled Install Curl on Windows Step 3

    3

    Click curl executable. This is usually the first listing in the menu.

  4. Image titled Install Curl on Windows Step 4

    4

    Click the drop-down under «Select Operating System» and select Windows 32 or 64. If your CPU is a 32-bit processor, you’ll need to download the 32-bit version; if your CPU is a 64-bit processor, you can download either, but the 64-bit version of cURL will take full advantage of your CPU’s benefits.[2]

  5. Image titled Install Curl on Windows Step 5

    5

    Click Select. This is next to the drop-down menu of available OS-compatible downloads.

  6. Image titled Install Curl on Windows Step 6

    6

    Select what version you want (only available for certain downloads, like Win32). Some builds of cURL, like with Win32, have different versions. Click the drop-down to select a version.

    • If «Generic» is available, choose that.
    • Click Select to continue. You’ll be directed to a page of recommended downloads.
  7. Image titled Install Curl on Windows Step 7

    7

    Click the arrow in the first result. This is usually a link to a download from the official cURL website.

  8. Image titled Install Curl on Windows Step 8

    8

    Click the build you want. You may have to choose between a 32-bit and 64-bit build again.

  9. Image titled Install Curl on Windows Step 9

    9

    Save the downloaded file. When your file browser pops up, choose a location to save the file and click Save.

  10. Image titled Install Curl on Windows Step 10

    10

    Extract the files from the zipped folder. A zipped file will download to the location you specified, and you’ll need to unzip the folder to continue.

    • Right-click on the folder and select ‘Extract All, then specify a location where you want to unzip the files to.
  11. Image titled Install Curl on Windows Step 11

    11

    Open the unzipped folder and files and find «curl.exe.«. You’ll find the root folder in the location you previously specified. And you’ll probably find «curl.exe» in the bin folder.

  12. Image titled Install Curl on Windows Step 12

    12

    Type «cmd» in the address bar of your file browser to launch a command window. You can also type «CMD» in the search area of the Start Menu.

  13. Image titled Install Curl on Windows Step 13

    13

    Type «curl» into the command window and press Enter. If you opened the command window from the address bar of file browser while you were navigated in the «bin» folder, command prompt should already have the appropriate address entered.

    • You should see command prompt return to you commands that you can try with curl.[3]
    • You can use the curl command on your computer from that specific path. If you type «curl» in command prompt at a path different from where it’s located (in the «bin» folder of the unzipped folder), it will not work.
  14. Advertisement

Ask a Question

200 characters left

Include your email address to get a message when this question is answered.

Submit

Advertisement

Thanks for submitting a tip for review!

References

About This Article

Article SummaryX

1. Go to https://curl.haxx.se/download.html in a web browser.

2. Click curl Download Wizard.

3. Click curl executable.
4. Click the drop-down under «Select Operating System» and select Windows 32 or 64.

5. Click Select.

6. Select what version you want (only available for certain downloads, like Win32).

7. Click the arrow in the first result.

8. Click the build you want.

9. Save the downloaded file.

10. Extract the files from the zipped folder.

11. Open the unzipped folder and files and find «curl.exe.»

12. Type «cmd» in the address bar of your file browser to launch a command window.

13. Type «curl» into the command window and press Enter.

Did this summary help you?

Thanks to all authors for creating a page that has been read 25,955 times.

Is this article up to date?

Thought I’d write exactly what I did (Windows 10, 64-bit):

From the download page https://curl.haxx.se/download.html choose the download wizard https://curl.haxx.se/dlwiz/

Choose curl executable.

Choose Win64.

Choose generic.

Choose any.

Choose x86_64.

Choose the first recommended option. For me this was:

curl version: 7.53.1 — SSL enabled SSH enabled. Provided by: Viktor Szakáts. This package is type curl executable You will get a pre-built ‘curl’ binary from this link (or in some cases, by using the information that is provided at the page this link takes you). You may or may not get ‘libcurl’ installed as a shared library/DLL.
The file is packaged using 7zip. 7zip is a file archiving format.

Click download.

You should have the file curl-7.53.1-win64-mingw.7z in your downloads folder.

Install 7-Zip if you don’t have it.

Right-click, 7-Zip, Extract Here. Copy and paste the extracted file somewhere like Z:Tools

If you look in the bin folder you’ll see curl.exe. If you double-click it a window will quickly flash up and vanish. To run it you need to use the Command Prompt. Navigate to the bin folder and type curl followed by your parameters to make a request. You must use double-quotes. Single quotes won’t work with curl on Windows.

Now you’ll want to add curl to a user’s Path variable so you don’t have to navigate to the right folder to run the program. Go to This PC, Computer, System Properties, Advanced system settings, authenticate as an administrator (you’re not running as admin, right? Right?) Environment Variables, System variables, look at the list and select Path, then Edit, then New, then, e.g.

Z:Toolscurl-7.53.1-win64-mingwbin

You can add a trailing backslash if you like, I don’t think it matters. Click move up until it’s at the top of the list, then you can see it easily from the previous screen. Click OK, OK, OK, then crack open a Command Prompt and you can run curl by typing curl from any folder, as any user. Don’t forget your double-quotes.

This is the answer I wish I’d had.

Edit me

Хотя Postman удобен, его трудно использовать для представления в документации, как совершать запросы с его помощью. Кроме того, разные пользователи, вероятно, используют разные клиенты с графическим интерфейсом или вообще не используют их (предпочитая командную строку)

Вместо того, чтобы описывать, как выполнять REST-запросы с использованием GUI-клиента, такого как Postman, наиболее традиционный метод документирования синтаксиса запроса — использовать curl.

curl — это утилита командной строки, которая позволяет выполнять HTTP-запросы с различными параметрами и методами. Вместо того, чтобы переходить к веб-ресурсам в адресной строке браузера, можно использовать командную строку, чтобы получить те же ресурсы, извлеченные в виде текста.

Установка curl

curl доступен на MacOS по умолчанию, для Windows требуется установка. Ниже представлены инструкции по установке curl.

Установка на MacOS

Проверить установлен ли curl на MacOS можно так:

  1. Открываем Терминал (нажимаем Cmd+spacebar для открытия Спотлайт и вводим Terminal).
  2. В терминале пишем curl -V. Ответ должен быть примерно таким:
curl 7.54.0 (x86_64-apple-darwin16.0) libcurl/7.54.0 SecureTransport zlib/1.2.8
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtsp smb smbs smtp smtps telnet tftp Features: AsynchDNS IPv6 Largefile GSS-API Kerberos SPNEGO NTLM NTLM_WB SSL libz UnixSockets

Если такого ответа нет, то curl необходимо скачать и установить

Установка на Windows

Установка curl в Windows включает другие шаги. Сначала определяем версию windows: 32-разрядная или 64-разрядная версия Windows, щелкнув правой кнопкой мыши Компьютер и выбрав Свойства. Затем следуем инструкциям на этой странице. Нужно выбрать одну из бесплатных версий с правами Администратора.

После установки проверяем версию установленной curl;

  1. Открываем командную строку нажав кнопку Пуск и введя cmd
  2. В строке пишем curl -V

Ответ должен быть примерно таким:

curl 7.54.0 (x86_64-apple-darwin14.0) libcurl/7.37.1 SecureTransport zlib/1.2.5
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtsp smtp smtps telnet tftp
Features: AsynchDNS GSS-Negotiate IPv6 Largefile NTLM NTLM_WB SSL libz

Создание тестового вызова API

После установки curl делаем тестовый вызов API

curl -X GET "https://api.openweathermap.org/data/2.5/weather?zip=95050&appid=fd4698c940c6d1da602a70ac34f0b147&units=imperial"

В ответ должен вернуться минимизированный JSON:

{"coord":{"lon":-121.96,"lat":37.35},"weather":[{"id":701,"main":"Mist","description":"mist","icon":"50d"}],"base":"stations","main":{"temp":66.92,"pressure":1017,"humidity":50,"temp_min":53.6,"temp_max":75.2},"visibility":16093,"wind":{"speed":10.29,"deg":300},"clouds":{"all":75},"dt":1522526400,"sys":{"type":1,"id":479,"message":0.0051,"country":"US","sunrise":1522504404,"sunset":1522549829},"id":420006397,"name":"Santa Clara","cod":200}

curl и Windows

Если вы используете Windows, обратите внимание на следующие требования к форматированию при использовании curl:

  • Используйте двойные кавычки в командной строке Windows. (Windows не поддерживает одинарные кавычки.);
  • Не используйте обратную косую черту для разделения строк. (Это только для удобства чтения и не влияет на вызов на Mac.)
  • Добавив -k в команду curl, вы можете обойти сертификат безопасности curl, который может быть необходимым.

🔙

Go next ➡

CURL – это инструмент командной строки и библиотека для передачи данных с URL-адресами.

Он бесплатен, и многие приложения используют его.

В этом руководстве мы расскажем, как установить CURL в Windows.

Несколько удивительно, что он используется в автомобилях, телевизорах, роутерах, принтерах, аудиоаппаратуре, мобильных телефонах, планшетах, телевизионных приставках, медиаплеерах и во многих других местах.

Содержание

  1. Установите CURL на Windows 10
  2. 1] Установите Git для Windows
  3. 2] Загрузите и установите Curl из исходников с сайта.
  4. 3] CURL установщик

Установите CURL на Windows 10

Начиная с Windows 10 v 1803, ОС теперь поставляется с копией CURL.

Он уже настроен, и вы можете сразу начать его использовать.

Откройте командную строку и введите «curl -help«.

Если ошибок нет и отображаются все параметры curl, он установлен на вашем Windows 10.

Наряду с Curl, Microsoft также выпустила Tar, инструмент командной строки для извлечения файлов и создания архивов.

Если по какой-то причине вы не можете найти CURL, установленный в вашей ОС Windows, вот как установить Curl в Windows.

1] Установите Git для Windows

Скачайте Git для Windows, и он установит CURL вместе в дагонку.

Вы можете найти его установленным в C:Program FilesGitmingw64bin.

Добавьте его в свой путь Windows, и вы сможете выполнить его из любого места.

Нажмите кнопку запуска и введите системный путь.

Появится опция для редактирования системных переменных.

Нажмите на переменные среды, и вы сможете добавить путь, как указано выше, в системный путь.

2] Загрузите и установите Curl из исходников с сайта.

Если Git не то, что вам нужно, вы можете скачать и установить CURL с официального сайта.

Перейдите сюда и загрузите соответствующий архив для вашей системы (32 или 64 бит).

Если вы хотите загрузить определенные пакеты, посетите страницу пакетов curl.

Здесь вы можете скачать исполняемый файл curl, разработку libcurl, libcurl или исходный код.

Убедитесь, что добавили исполняемый файл к вашему пути.

3] CURL установщик

Если вы предпочитаете установку в один клик, используйте  установщик cURL для Windows.

Вы можете скачать его здесь.

Все это установит CURL на Windows.

Если вы разрабатываете что-то или ваше приложение требует CURL для работы на вашем компьютере, руководство вам в помощь.

Setup cURL in Windows

cURL (client URL) is a command line tool that system admins and developers use to transfer data between server and client in the form of a URL. It supports several different protocols and has a variety of applications. I will not cover the details and applications of cRUL here. If you’re already on this page, I am assuming you know how to use it. Learn how to use curl in Windows if you are just getting started with it.

cURL in Windows 10 version 1803 or higher

Starting with Windows 10 (version 1803) or Server 2019, you will find curl.exe pre-installed in your %systemroot%System32 directory by default. This guide is useful if you are on an older Windows version or you want to use the latest curl version from official website, which supports more protocols than the built-in curl version. I will also cover how to fix some most common errors that you might face while using cURL in Windows.

Most Common Errors with Secure Websites

You will get a whole lot of different errors while using secure URLs with cURL. So if you’re getting any error among the below mentioned errors, you are on the right page.

curl: (35) schannel: next InitializeSecurityContext failed

curl: (35) schannel: next InitializeSecurityContext failed: Unknown error (0x80092012) - The revocation function was unable to check revocation for the certificate.

curl - (35) schannel - next InitializeSecurityContext failed - Unknown error (0x80092012)

If you get this error message, it indicates that curl was unable to check revocation for the certificate which is the default behavior when it comes to communication with secure websites. Even though you could easily circumvent this error by using the --ssl-no-revoke argument with curl command but it becomes tedious when you use curl command a lot. The following command shows how to bypass this error:

curl --ssl-no-revoke --head https://www.techtutsonline.com/

To learn how to get around this error once and for all – without having to specify the --ssl-no-revoke argument each time, see the Setup the latest version of cURL in Windows section.

curl: (60) SSL certificate problem

curl: (60) SSL certificate problem: unable to get local issuer certificate

curl - (60) SSL certificate problem - unable to get local issuer certificate

If you get this error, it means there is something wrong with root certificate that curl is using on your local system. To get around this error, you could use the --insecure (or -k for short) argument with curl command as shown in the following command:

curl --insecure https://www.techtutsonline.com/

Again, to learn how to get around this error once and for all, see the Setup the latest version of cURL in Windows section.

curl: (60) schannel: CertGetCertificateChain trust error

curl: (60) schannel: CertGetCertificateChain trust error CERT_TRUST_IS_UNTRUSTED_ROOT

curl - (60) schannel - CertGetCertificateChain trust error CERT_TRUST_IS_UNTRUSTED_ROOT

If you see this error, it means the root CA that curl is configured to use is untrusted. It may be using a self-signed certificate or the certificate is no longer valid. This error can also be bypassed by using the --insecure argument with curl command as shown in previous example.

Setup the latest version of cURL in Windows

Depending upon the edition of your Windows, you can download the latest version of cURL from the official website using the following links:

  • For 64-bit Windows
  • For 32-bit Windows

It will download a zip archive. There is no installer in this file so you will have to manually set the PATH environment for curl.exe binary. Once downloaded, you can extract the zip archive to any folder of your choice. I extracted mine inside D:WORKSOFTWAREcurl-7.81.0-win64 directory. Your directory should look like shown in the following screenshot:

curl directory path

Now to set the PATH environment variable, open RUN dialog (WinLogoKey+R), type “sysdm.cpl ,3” without quotes and press enter. This will open up advanced system properties page. Now follow the steps mentioned in the screenshot and click on OK thrice to save the changes.

Add CURL to Path Environment VariableMake sure you specify the correct path to bin directory in STEP 5. I added D:WORKSOFTWAREcurl-7.81.0-win64bin in my case.

When this is done, curl is ready to be used on your system. To confirm, you can open the command prompt and type curl --version command. If you see the curl version as shown in the following image, you’re all set to go to next step:
Check curl version
If you get an error that says ‘curl’ is not recognized as an internal or external command, operable program or batch file, it means something is wrong with the PATH environment variable you created.
'curl' is not recognized as an internal or external command, operable program or batch file
If you see this error, please follow the steps mentioned in this video to properly setup your PATH environment variable.

Certificate Setup for cURL

Now comes the most important part. At this point, when you try any secure URL with curl command, you will most probably get an error as we discussed in past sections. To permanently fix those SSL errors, you need to download the CA certificate file from official website and configure the curl on your system to use that certificate file. To do that, follow these steps:

  1. First of all, download the CA certificate file and copy it into the same directory where curl.exe file is available. To get the location of curl.exe, you could simply type where curl command in your command prompt.
    locate curl curl
  2. Now create a new file named .curlrc in the same directory as that of curl.exe. In the end, your curl directory should look like shown in the following image:
    set curl to use the cacert in .curlrc file
  3. Now open the .curlrc file in notepad (or any other text editor) and set the complete path of root certificate file that you downloaded in first step. See the screenshot for reference:
    set cacert path in .curlrc file
    Please remember to use the forward slash (/) while specifying directory path as shown below otherwise it won’t work:

    cacert = "D:/WORK/SOFTWARE/curl-7.81.0-win64/bin/cacert.pem"
    
  4. [optional] If you’re using Windows 10 (version 1803) or higher, your system will most likely have curl.exe in %systemroot%System32 directory as well. When you will run curl command without explicitly specifying the complete path to curl.exe executable, your system will use the default executable located in %systemroot%System32. If this is true you will see curl.exe twice when you run where curl command. See the following image for reference:
    locate curl executable duplicate
    If you see the same, you need to get rid of default curl.exe that comes with Windows. You can take the ownership of file, set the permissions and then rename the file with the help of following commands:

    cd C:WindowsSystem32 
    takeown /a /f curl.exe
    icacls curl.exe /grant administrators:F
    ren curl.exe curl.exe.bak

    Make sure you run these commands in an elevated command prompt. See the following screenshot for reference:
    take ownership of default curl and rename

  5. Once you successfully rename the default curl.exe executable, you should see a single instance of curl.exe when running where curl command.
  6. Your system is now all set and you can start using curl without any SSL error. The following screenshot shows that I no longer get any SSL error and I don’t have to use the --insecure or --ssl-no-revoke arguments anymore.
    curl -I https://www.techtutsonline.com/

    curl success

Curl (client URL) is a command-line tool powered by the libcurl library to transfer data to and from the server using various protocols, such as HTTP, HTTPS, FTP, FTPS, IMAP, IMAPS, POP3, POP3S, SMTP, and SMTPS. It is highly popular for automation and scripts due to its wide range of features and protocol support. In this article, you will learn how to use curl in Windows with various examples. Let’s get started.

Contents

  1. Install curl on Windows
  2. Curl syntax
  3. HTTP GET request
  4. Get remote file information.
  5. Download a file
  6. Resume interrupted download
  7. Authentication with Curl
  8. Upload a file
  9. Quote a command
  10. Change the user-agent
  11. Send a cookie
  12. Use a proxy server
  13. Additional request headers
  14. Send an email
  • Author
  • Recent Posts

Surender Kumar has more than twelve years of experience in server and network administration. His fields of interest are Windows Servers, Active Directory, PowerShell, web servers, networking, Linux, virtualization, and penetration testing. He loves writing for his blog.

Latest posts by Surender Kumar (see all)

  • Extending LVM space in Ubuntu — Thu, Feb 2 2023
  • Backup in Proxmox VE — Thu, Jan 26 2023
  • Snapshots in Proxmox VE — Wed, Jan 25 2023

Install curl on Windows

All the modern Windows versions, starting with Windows 10 (version 1803) and Server 2019, have the curl executable pre-installed, so there is no need for a manual installation. To determine the curl location and version in your system, you can use the following commands:

where curl
curl --version

Determine the location and version of curl in Windows

Determine the location and version of curl in Windows

The curl —version command also lists the protocols and features supported by the current curl version. If you see an output, as shown in the screenshot above, you’re all set to use the built-in curl utility. If you get an error message instead, curl might not be available, probably because you’re on an earlier version of Windows (e.g., Windows 8.1 or Server 2016). In that case, you might need to manually setup curl in Windows.

Curl syntax

The curl command uses the following syntax:

curl [options...] [url]

It supports various options, which we will discuss later in this post. As with any other command-line tool, you can use the curl —help command to get help.

Getting help with the curl command

Getting help with the curl command

To get detailed help, you can use curl —help all. The help section is divided into categories, so the curl —help category gets you an overview of all the categories.

Now that you’ve become familiar with curl syntax, let’s discuss various use cases with the help of examples.

HTTP GET request

When you use curl against a URL without specifying any option, the request defaults to the GET method of the HTTP protocol. Try this:

curl https://4sysops.com

The above command is essentially equivalent to curl —request GET https://4sysops.com, which sends a GET request to 4sysops.com using the HTTPS protocol. To specify the HTTP protocol version (e.g., http/2), use the —http2 option, as shown below:

curl --http2 https://4sysops.com

For URLs starting with HTTPS, curl first tries to negotiate to establish a http/2 connection and automatically falls back to http/1.1 if the negotiation fails. It also supports other methods, such as HEAD, POST, PUT, and DELETE. To use these methods, along with the curl command, use the —request (or -X) option, followed by the method. Notice that the methods that are available depend on the protocol being used.

Get remote file information.

As an admin, you might want to be interested in HTTP headers only. This can be done using the —head (or -I) option. Sometimes, a URL might redirect you to another location. In that case, —location (or -L) allows the curl to follow the redirects. You can also use —insecure (or -k) to allow insecure connections to avoid any TLS certificate errors if the target URL is using a self-signed certificate. Use this only when absolutely necessary. All three of these options can be combined in short-notation, as shown in the following command:

curl -kIL 4sysops.com

View request headers allow insecure connection and follow redirect options with curl

View request headers allow insecure connection and follow redirect options with curl

You can see that short-notation is particularly useful for combining multiple options. The above command is essentially equivalent to the curl —insecure —head —location 4sysops.com command.

The —head (or -I) option also gives you basic information about a remote file without actually downloading it. As shown in the screenshot below, when you use curl with a remote file URL, it displays various headers to give you information about the remote file.

curl -IL https://curl.se/windows/dl-7.85.0_5/curl-7.85.0_5-win64-mingw.zip

Use curl to view the basic information about remote files

Use curl to view the basic information about remote files

The Content-Length header indicates the size of the file (in bytes), Content-Type reveals the media type of the file (for instance image/png, text/htm), Server indicates the type of server application (Apache, Gunicron, etc.), Last-Modified shows the date when file was last changed on the server, and the Accept-Ranges header indicates the support of partial requests from the client for downloads, which essentially means you can resume an interrupted download.

Download a file

You can use curl with the —remote-name option (or -O, in short) to download a file and save it with the same name as on the server. The following command downloads the latest version of curl for Windows from the official website:

curl -OL https://curl.se/windows/latest.cgi?p=win64-mingw.zip

Downloading a file with a default name and progress indicator using curl

Downloading a file with a default name and progress indicator using curl

The -L option is added to follow redirects, if needed, for locating the resource. If you want to save the file with a new name, use the —output (or -o) option instead. Furthermore, while using the curl command in a script, you might want to suppress the progress indicator using —silent (or -s). Both options can be combined, as shown in the following command:

curl -sLo curl.zip https://curl.se/windows/latest.cgi?p=win64-mingw.zip

Silently download a file and save with a custom name using curl

Silently download a file and save with a custom name using curl

Resume interrupted download

The presence of Accept-Ranges: bytes in the response header literally means that the server supports resumable downloads. To resume an interrupted download, you can use —continue-at (or -C), which accepts an offset (in bytes). Generally, specifying an offset is tricky, so curl offers an easy way of resuming an interrupted download:

curl -OLC - https://releases.ubuntu.com/22.04/ubuntu-22.04.1-desktop-amd64.iso 

Resuming an interrupted download with curl

Resuming an interrupted download with curl

As you can see in the screenshot, I was downloading an Ubuntu iso file, which was interrupted. When I ran the curl command again with the -C option, the transfer was resumed from the byte range where it was interrupted. The minus sign () next to -C allows the curl to automatically figure out how and where to resume the interrupted download.

Authentication with Curl

Curl also supports authentication, allowing you to download a protected file by supplying credentials with the —user (or -u) option, which accepts a username and password in the username:password format. If you skip typing the password, curl will prompt you to type it in no-echo mode.

curl -u surender -OL https://techtutsonline.com/secretFiles/sample.zip

Downloading a file using username and password authentication with curl

Downloading a file using username and password authentication with curl

If you use a basic authentication method, you have to transfer a username and password, which means that you should use a secure protocol such as HTTPS (instead of HTTP) or FTPS (instead of FTP). If, for some reason, you have to use an unencrypted protocol, make sure you use an authentication method that doesn’t transmit credentials in clear text (for instance, Digest, NTLM, or Negotiate authentication).

Curl also supports the use of .curlrc, _curlrc, and .netrc config files, allowing you to define various curl options in a file and then to include the file in your command with curl —config (or curl -K), which is particularly useful for scripting.

Upload a file

The —upload-file (or -T) option allows you to upload a local file to a remote server. The following command shows how to upload a file from a local system to a remote web server using the FTPS protocol:

curl -kT C:UsersSurenderDownloadssample1.zip -u testlabsurender ftps://192.168.0.80/awesomewebsite.com/files/

Uploading a file to a remote server using curl

Uploading a file to a remote server using curl

The -k option is included to avoid certificate errors if the web server uses a self-signed certificate. The trailing slash at the end of the URL tells curl that the destination is a directory. You could specify multiple file names, such as “{sample1.zip,sample2.zip}.” The following command shows how to upload multiple files with a single curl command:

curl -kT sample[1-5].zip -u testlabsurender ftps://192.168.0.80/awesomewebsite.com/files/

Upload multiple files to a remote server using curl

Upload multiple files to a remote server using curl

Quote a command

As already discussed, curl supports various methods based on the underlying protocol being used. You can send additional commands using —quote (or -Q) to perform a particular operation either before or after the regular curl operation; for instance, if you want to download a file from a remote server using the FTPS protocol and want the file to be removed from the server once it has been downloaded successfully. To do this, you can run the command shown below:

curl -u testlabsurender -kO "ftps://192.168.0.80/awesomewebsite.com/files/sample1.zip" -Q "-DELE sample1.zip"

Delete a file after successful download using curl command

Delete a file after successful download using curl command

Here, I downloaded the sample1.zip file from an FTPS server with the help of the -O option. After the -Q option, I added a minus sign (-) just before the DELE command, which tells the curl to send the DELE sample1.zip command immediately after the file is downloaded successfully. Likewise, if you want to send a command to the server before performing the actual curl operation, use a plus (+) sign instead of a minus sign.

Change the user-agent

The user-agent tells a server what type of client is sending the request. When you send a curl request to the server, the curl/<version> user-agent is used by default. If the server is configured to block the curl requests, you can specify a custom user-agent using —user-agent (or -A). The following command sends a common Google Chrome user-agent:

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

Use a custom user agent with a curl command to avoid server blocks

Use a custom user agent with a curl command to avoid server blocks

The above screenshot shows that a normal curl request was forbidden by the web server (with a 403 Forbidden response), but when I passed a custom user-agent, the request was successful, returning a 200 OK response.

Send a cookie

By default, the curl request does not send or store cookies. To write a cookie, use the —cookie-jar (or -c) option, and with —cookie (or -b), you can send a cookie:

curl -c /path/cookie_file https://awesomewebsite.com/
curl -b /path/cookie_file https://awesomewebsite.com/

The first command writes a cookie file, and the second command sends the cookie with a curl request. You can also send a cookie in ‘name = value’‘ format, as shown below:

curl -b 'session=abcxyz' -b 'loggedin=true' http://echo.hoppscotch.io

Send multiple cookies using a curl command

Send multiple cookies using a curl command

I used the echo.hoppscotch.io website to view HTTP request headers that aren’t normally visible to clients sending a request. If you don’t want to use this website, you could use the –verbose (or -v) option to see your request in raw form (which will show request headers, too).

Use a proxy server

Do you use a proxy server to connect to the internet? No problem! Curl lets you specify a proxy server using the —proxy (or -x) option. If your proxy server requires authentication, add —proxy-user (or -U):

curl -x 192.168.0.250:8088 -U username:password https://awesomewebsite.com/

The proxy server is specified in the server:port format, and the proxy user is specified in the username:password format. Again, you could skip typing the password for the proxy user, and curl will prompt you to enter it in no-echo mode.

Use a proxy server and authentication with a curl command

Use a proxy server and authentication with a curl command

Additional request headers

Sometimes, you might want to send additional information along with your request to the server. With curl, you can do so easily by using —header (or -H), as shown in the following command:

curl -vkIH "x-client-os: Windows 11 Enterprise (x64)" https://awesomewebsite.com

Specify additional headers with a curl request

Specify additional headers with a curl request

You could send any information that isn’t available with standard HTTP request headers. In this example, I sent my operating system name. I also added the -v option this time to enable verbose output, which displayed the additional header being sent along with my curl request.

Send an email

Since curl supports the SMTP protocol, you could use it to send an email message. The following command shows how to send an email using 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

Send an email message using a curl command

Send an email message using a curl command

Let’s quickly discuss the options used:

  • The —insecure (or -k) command is used to avoid an SSL certificate error. We have used this before.
  • The —ssl-reql option is used to upgrade a plain-text connection to encrypted connection if supported by the SMTP server. Alternatively, if you’re sure your SMTP server supports SSL, you could directly use the smtps server name (e.g., smtps://smtp.yourdomain.com), as you can see in the screenshot.
  • The —mail-from option is used to define the sender’s (from) email address.
  • The mail-rcpt option specifies the recipient’s email address.
  • The —user (or -u) option sends the username for authentication, which should match the mail-from address, because otherwise your message might be rejected or flagged as spam.
  • The —upload-file (or -T) option is used to specify a file that contains the email message to send.

The following screenshot shows the email message I received in my inbox:

Viewing the email message sent with curl

Viewing the email message sent with curl

Viewing the email message sent with curl

Subscribe to 4sysops newsletter!

These are just a few examples, but there is a lot more you can do with curl. I highly recommend checking out curl help and experimenting with it. You’ll notice what a powerful command curl is.

Like this post? Please share to your friends:
  • Как установить cudnn в windows 10
  • Как установить cubase 10 на windows 10
  • Как установить crysis 3 на windows 10 64 bit
  • Как установить cry of fear на windows 10
  • Как установить cortana на windows 10