Что такое curl и как работает эта команда

Формы

Формы — основной способ представления web-сайта как HTML-страницы
с полями, в которые пользователь вводит данные, и затем нажимает на
кнопку ‘OK’ или ‘Отправить’, после чего данные отсылаются на сервер.
Затем сервер использует принятые данные и решает, как действовать
дальше: искать информацию в базе данных, показать введенный адрес на
карте, добавить сообщение об ошибке или использовать информацию для
аутентификации пользователя. Разумеется, на стороне сервера имеется
какая-то программа, которая принимает ваши данные.

4.1 GET

GET-форма использует метод GET, например следующим образом:

        <form method="GET" action="junk.cgi">
        <input type=text name="birthyear">
        <input type=submit name=press value="OK">
        </form>

Если вы откроете этот код в вашем браузере, вы увидите форму с
текстовым полем и кнопку с надписью «OK». Если вы введете
‘1905’ и нажмете OK, браузер создаст новый URL, по которому и
проследует. URL будет представляться строкой, состоящей из пути
предыдущего URL и строки, подобной
«junk.cgi?birthyear=1905&press=OK».

Например, если форма располагалась по адресу
«www.hotmail.com/when/birth.html», то при нажатии на кнопку
OK вы попадете на URL
«www.hotmail.com/when/junk.cgi?birthyear=1905&press=OK».

Большинство поисковых систем работают таким образом.

Чтобы curl сформировал GET-запрос, просто введите то, что
ожидалось от формы:

        # curl "www.hotmail.com/when/junk.cgi?birthyear=1905&press=OK"

4.2 POST

Метод GET приводит к тому, что вся введенная информация
отображается в адресной строке вашего браузера. Может быть это
хорошо, когда вам нужно добавить страницу в закладки, но это
очевидный недостаток, когда вы вводите в поля формы секретную
информацию, либо когда объем информации, вводимый в поля, слишком
велик (что приводит к нечитаемому URL).

Протокол HTTP предоставляет метод POST. С помощью него клиент
отправляет данные отдельно от URL и поэтому вы не увидете их в
адресной строке.

Форма, генерирующая POST-запрос, похожа на предыдущую:

        <form method="POST" action="junk.cgi">
        <input type=text name="birthyear">
        <input type=submit name=press value=" OK ">
        </form>

Curl может сформировать POST-запрос с теми же данными следующим
образом:

        # curl -d "birthyear=1905&press=%20OK%20" www.hotmail.com/when/junk.cgi

Этот POST-запрос использует ‘Content-Type
application/x-www-form-urlencoded’, это самый широко используемый
способ.

Данные, которые вы отправляете к серверу, должны быть правильно
закодированы
, curl не будет делать это за вас. К примеру, если вы
хотите, чтобы данные содержали пробел, вам нужно заменить этот пробел
на %20 и т.п. Недостаток внимания к этому вопросу — частая ошибка,
из-за чего данные передаются не так, как надо.

4.3 Загрузка файлов с помощью POST (File Upload POST)

В далеком 1995 был определен дополнительный способ передавать
данные по HTTP. Он задокументирован в RFC 1867, поэтому этот способ
иногда называют RFC1867-posting.

Этот метод в основном разработан для лучшей поддержки загрузки
файлов. Форма, которая позволяет пользователю загрузить файл,
выглядит на HTML примерно следующим образом:

        <form method="POST" enctype='multipart/form-data' action="upload.cgi">
        <input type=file name=upload>
        <input type=submit name=press value="OK">
        </form>

Заметьте, что тип содержимого Content-Type установлен в
multipart/form-data.

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

        # curl -F upload=@localfilename -F press=OK 

4.4 Скрытые поля

Обычный способ для передачи информации о состоянии в
HTML-приложениях — использование скрытых полей в формах. Скрытые поля
не заполняются, они невидимы для пользователя и передаются так же,
как и обычные поля.

Простой пример формы с одним видимым полем, одним скрытым и
кнопкой ОК:

        <form method="POST" action="foobar.cgi">
        <input type=text name="birthyear">
        <input type=hidden name="person" value="daniel">
        <input type=submit name="press" value="OK">
        </form>

Чтобы отправить POST-запрос с помощью curl, вам не нужно думать о
том, скрытое поле или нет. Для curl они все одинаковы:

        # curl -d "birthyear=1905&press=OK&person=daniel" 

4.5 Узнать, как выглядит POST-запрос

Когда вы хотите заполнить форму и отослать данные на сервер с
помощью curl, вы наверняка хотите, чтобы POST-запрос выглядел точно
также, как и выполненный с помощью браузера.

Простой способ увидеть свой POST-запрос, это сохранить
HTML-страницу с формой на диск, изменить метод на GET, и нажать
кнопку ‘Отправить’ (вы можете также изменить URL, которому будет
передаваться данные).

Вы увидите, что данные присоединились к URL, отделенные символами
‘?’, как и предполагается при использовании GET-форм.

Что такое curl?

На самом деле, curl — это больше чем просто утилита командной строки для Linux или Windows. Это набор библиотек, в которых реализуются базовые возможности работы с URL страницами и передачи файлов. Библиотека поддерживает работу с протоколами: FTP, FTPS, HTTP, HTTPS, TFTP, SCP, SFTP, Telnet, DICT, LDAP, а также POP3, IMAP и SMTP. Она отлично подходит для имитации действий пользователя на страницах и других операций с URL адресами.

Поддержка библиотеки curl была добавлена в множество различных языков программирования и платформ. Утилита curl — это независимая обвертка для этой библиотеки. Именно на этой утилите мы и остановимся в этой статье.

Step 3 — Following Redirects

Thus far all of the examples have included fully qualified URLs that include the protocol. If you happened to try to fetch the file and only specified , you would not see any output, because DigitalOcean redirects requests from to :

You can verify this by using the flag, which displays the request headers rather than the contents of the file:

The output shows that the URL was redirected. The first line of the output tells you that it was moved, and the line tells you where:

You could use to make another request manually, or you can use the or argument which tells to redo the request to the new location whenever it encounters a redirect. Give it a try:

This time you see the output, as followed the redirect:

You can combine the argument with some of the aforementioned arguments to download the file to your local system:

Warning: Many resources online will ask you to use to download scripts and execute them. Before you run any scripts you have downloaded, it’s good practice to check their contents before making them executable and running them. Use the command to review the code to ensure it’s something you want to run.

User Agent

An HTTP request has the option to include information about the browser that generated the request. Curl allows it to be specified on the command line. It is especially useful to fool or trick stupid servers or CGI scripts that only accept certain browsers.

Example:

Other common strings:

  • — Netscape Version 3 for Windows 95
  • — Netscape Version 3 for Windows 95
  • — Netscape Version 2 for OS/2
  • — Netscape for AIX
  • — Netscape for Linux

Note that Internet Explorer tries hard to be compatible in every way:

Mozilla/4.0 (compatible; MSIE 4.01; Windows 95) — MSIE for W95

Mozilla is not the only possible User-Agent name:

  • — KDE File Manager desktop client
  • — Lynx command line browser

HTTPS is HTTP secure

There are a few ways to do secure HTTP transfers. By far the most common protocol for doing this is what is generally known as HTTPS, HTTP over SSL. SSL encrypts all the data that is sent and received over the network and thus makes it harder for attackers to spy on sensitive information.

SSL (or TLS as the latest version of the standard is called) offers a truckload of advanced features to allow all those encryptions and key infrastructure mechanisms encrypted HTTP requires.

Curl supports encrypted fetches when built to use a TLS library and it can be built to use one out of a fairly large set of libraries — will show which one your curl was built to use (if any!). To get a page from a HTTPS server, simply run curl like:

Как пользоваться curl?

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

Загрузка файлов

Самая частая задача — это загрузка файлов linux. Скачать файл очень просто. Для этого достаточно передать утилите в параметрах имя файла или html страницы:

curl https://raw.githubusercontent.com/curl/curl/master/README.md

Но тут вас ждет одна неожиданность, все содержимое файла будет отправлено на стандартный вывод. Чтобы записать его в какой-либо файл используйте:

curl -o readme.txt https://raw.githubusercontent.com/curl/curl/master/README.md

А если вы хотите, чтобы полученный файл назывался так же, как и файл на сервере, используйте опцию -O:

curl -O https://raw.githubusercontent.com/curl/curl/master/README.md

Если загрузка была неожиданно прервана, вы можете ее возобновить:

curl -# -C — -O https://cdn.kernel.org/pub/linux/kernel/v4.x/testing/linux-4.11-rc7.tar.xz

Если нужно, одной командой можно скачать несколько файлов:

curl -O https://raw.githubusercontent.com/curl/curl/master/README.md -O https://raw.githubusercontent.com/curl/curl/master/README

Еще одна вещь, которая может быть полезной администратору — это загрузка файла, только если он был изменен:

curl -z 21-Dec-17 https://raw.githubusercontent.com/curl/curl/master/README.md -O https://raw.githubusercontent.com/curl/curl/master/README

Данная команда скачает файл, только если он был изменен после 21 декабря 2017.

Ограничение скорости

Вы можете ограничить скорость загрузки до необходимого предела, чтобы не перегружать сеть с помощью опции -Y:

curl —limit-rate 50K -O https://cdn.kernel.org/pub/linux/kernel/v4.x/testing/linux-4.11-rc7.tar.xz

Здесь нужно указать количество килобайт в секунду, которые можно загружать. Также вы можете разорвать соединение если скорости недостаточно, для этого используйте опцию -Y:

curl -Y 100 -O https://raw.githubusercontent.com/curl/curl/master/README.md

Передача файлов

Загрузка файлов, это достаточно просто, но утилита позволяет выполнять и другие действия, например, отправку файлов на ftp сервер. Для этого существует опция -T:

curl -T login.txt ftp://speedtest.tele2.net/upload/

Или проверим отправку файла по HTTP, для этого существует специальный сервис:

curl -T ~/login.txt http://posttestserver.com/post.php

В ответе утилита сообщит где вы можете найти загруженный файл.

Отправка данных POST

Вы можете отправлять не только файлы, но и любые данные методом POST. Напомню, что этот метод используется для отправки данных различных форм. Для отправки такого запроса используйте опцию -d. Для тестирования будем пользоваться тем же сервисом:

curl -d «field1=val&fileld2=val1″http://posttestserver.com/post.php

Если вас не устраивает такой вариант отправки, вы можете сделать вид, что отправили форму. Для этого есть опция -F:

curl -F «password=@pass;type=text/plain» http://posttestserver.com/post.php

Здесь мы передаем формой поле password, с типом обычный текст, точно так же вы можете передать несколько параметров.

Передача и прием куки

Куки или Cookie используются сайтами для хранения некой информации на стороне пользователя. Это может быть необходимо, например, для аутентификации. Вы можете принимать и передавать Cookie с помощью curl. Чтобы сохранить полученные Cookie в файл используйте опцию -c:

curl -c cookie.txt http://posttestserver.com/post.php

Затем можно отправить cookie curl обратно:

curl -b cookie.txt http://posttestserver.com/post.php

Передача и анализ заголовков

Не всегда нам обязательно нужно содержимое страницы. Иногда могут быть интересны только заголовки. Чтобы вывести только их есть опция -I:

curl -I https://losst.ru

А опция -H позволяет отправить нужный заголовок или несколько на сервер, например, можно передать заголовок If-Modified-Since чтобы страница возвращалась только если она была изменена:

curl -I —хедер ‘If-Modified-Since: Mon, 26 Dec 2016 18:13:12 GMT’ https://losst.ru

Аутентификация curl

Если на сервере требуется аутентификация одного из распространенных типов, например, HTTP Basic или FTP, то curl очень просто может справиться с такой задачей. Для указания данных аутентификации просто укажите их через двоеточие в опции -u:

curl -u ftpuser:ftppass -T — ftp://ftp.testserver.com/myfile_1.txt

Точно так же будет выполняться аутентификация на серверах HTTP.

Использование прокси

Если вам нужно использовать прокси сервер для загрузки файлов, то это тоже очень просто. Достаточно задать адрес прокси сервера в опции -x:

curl -x proxysever.test.com:3128 http://google.co.in

Curl и FTP

Утилита поддерживает FTP! Вы можете использовать её для загрузки файлов с удалённого сервера.

curl -u username:password -O ftp://sampleftpserver/testfile.tar.gz

В приведённой выше команде ftp://sampleftpserver — это FTP-сервер, который принимает соединения. Вы можете не указывать имя пользователя и пароль для анонимных FTP-соединений. Введите команду и посмотрите, как заполняется индикатор выполнения.

Вы также можете загружать файлы с помощью этой команды:

curl -u username:password -T testfile.tar.gz ftp://sampleftpserver

Опять же таки, мы можем пропустить имя пользователя и пароль для анонимных FTP-соединений.

Proxy

curl supports both HTTP and SOCKS proxy servers, with optional authentication. It does not have special support for FTP proxy servers since there are no standards for those, but it can still be made to work with many of them. You can also use both HTTP and SOCKS proxies to transfer files to and from FTP servers.

Get an ftp file using an HTTP proxy named my-proxy that uses port 888:

Get a file from an HTTP server that requires user and password, using the same proxy as above:

Some proxies require special authentication. Specify by using -U as above:

A comma-separated list of hosts and domains which do not use the proxy can be specified as:

If the proxy is specified with instead of or , then curl will use HTTP/1.0 instead of HTTP/1.1 for any attempts.

curl also supports SOCKS4 and SOCKS5 proxies with and .

See also the environment variables Curl supports that offer further proxy control.

Most FTP proxy servers are set up to appear as a normal FTP server from the client’s perspective, with special commands to select the remote FTP server. curl supports the , and options that can be used to set up transfers through many FTP proxies. For example, a file can be uploaded to a remote FTP server using a Blue Coat FTP proxy with the options:

See the manual for your FTP proxy to determine the form it expects to set up transfers, and curl’s option to see exactly what curl is sending.

TELNET

The curl telnet support is basic and very easy to use. Curl passes all data passed to it on stdin to the remote server. Connect to a remote telnet server using a command line similar to:

And enter the data to pass to the server on stdin. The result will be sent to stdout or to the file you specify with .

You might want the / option to switch off the buffered output for slow connections or similar.

Pass options to the telnet protocol negotiation, by using the option. To tell the server we use a vt100 terminal, try something like:

Other interesting options for it include:

  • Sets the X display location.
  • Sets an environment variable.

NOTE: The telnet protocol does not specify any way to login with a specified user and password so curl can’t do that automatically. To do that, you need to track when the login prompt is received and send the username and password accordingly.

Using Passwords

To ftp files using name+passwd, include them in the URL like:

or specify them with the -u flag like

It is just like for FTP, but you may also want to specify and use SSL-specific options for certificates etc.

Note that using as prefix is the «implicit» way as described in the standards while the recommended «explicit» way is done by using FTP:// and the option.

This is similar to FTP, but you can use the option to specify a private key to use instead of a password. Note that the private key may itself be protected by a password that is unrelated to the login password of the remote system; this password is specified using the option. Typically, curl will automatically extract the public key from the private key file, but in cases where curl does not have the proper library support, a matching public key file must be specified using the option.

HTTP

Curl also supports user and password in HTTP URLs, thus you can pick a file like:

or specify user and password separately like in

HTTP offers many different methods of authentication and curl supports several: Basic, Digest, NTLM and Negotiate (SPNEGO). Without telling which method to use, curl defaults to Basic. You can also ask curl to pick the most secure ones out of the ones that the server accepts for the given URL, by using .

Note! According to the URL specification, HTTP URLs can not contain a user and password, so that style will not work when using curl via a proxy, even though curl allows it at other times. When using a proxy, you must use the style for user and password.

Background

This document assumes that you’re familiar with HTML and general networking.

The increasing amount of applications moving to the web has made «HTTP Scripting» more frequently requested and wanted. To be able to automatically extract information from the web, to fake users, to post or upload data to web servers are all important tasks today.

Curl is a command line tool for doing all sorts of URL manipulations and transfers, but this particular document will focus on how to use it when doing HTTP requests for fun and profit. I will assume that you know how to invoke or to get basic information about it.

Curl is not written to do everything for you. It makes the requests, it gets the data, it sends data and it retrieves the information. You probably need to glue everything together using some kind of script language or repeated manual invokes.

?‍? Опрос

Проверьте свою внимательность. Что означают следующие параметры?

Tip: Использование curl в Терминале или iTerm OS Mac обеспечивают намного более простую работу, чем использование командной строки в Windows. Если серьезно относиться к документации API, работая на ПК, стоит подумать о переходе с OS Windows. Будет много утилит, которые мы установим при помощи Терминала, который просто работает на Mac. Кроме того, находясь в Силиконовой долине, и используя ПК вместо Mac можно показаться старомодным для окружающих (см. Почему большинство стартапов покупают MacBook для своих сотрудников).

Для более подробного изучения curl в документировании REST API можно посмотреть REST-esting with curl.

HTTPS

Secure HTTP requires a TLS library to be installed and used when curl is built. If that is done, curl is capable of retrieving and posting documents using the HTTPS protocol.

Example:

curl is also capable of using client certificates to get/post files from sites that require valid certificates. The only drawback is that the certificate needs to be in PEM-format. PEM is a standard and open format to store certificates with, but it is not used by the most commonly used browsers. If you want curl to use the certificates you use with your (favourite) browser, you may need to download/compile a converter that can convert your browser’s formatted certificates to PEM formatted ones.

Example on how to automatically retrieve a document using a certificate with a personal password:

If you neglect to specify the password on the command line, you will be prompted for the correct password before any data can be received.

Many older HTTPS servers have problems with specific SSL or TLS versions, which newer versions of OpenSSL etc use, therefore it is sometimes useful to specify what SSL-version curl should use. Use -3, -2 or -1 to specify that exact SSL version to use (for SSLv3, SSLv2 or TLSv1 respectively):

Otherwise, curl will attempt to use a sensible TLS default version.

Команды Curl для HTTP

Curl также можно использовать c прокси-сервером. Если вы находитесь за прокси-сервером, прослушивающим порт 8090 на sampleproxy.com, загрузите файлы, как показано ниже:

curl -x  sampleproxy.com:8090 -U username:password -O http:// testdomain.com/testfile.tar.gz

В приведённом выше примере вы можете выбросить -U username:password, если прокси-сервер не требует метода аутентификации.

Типичный HTTP-запрос всегда содержит заголовок. Заголовок HTTP отправляет дополнительную информацию об удалённом веб-сервере вместе с фактическим запросом. С помощью инструментов разработчика в браузере вы можете посмотреть сведения о заголовке, а проверить их можно с помощью команды curl.

Пример ниже демонстрирует, как получить информацию о заголовке с веб-сайта.

curl -I www.testdomain.com

Используя curl, вы можете сделать запрос GET и POST. Запрос GET будет выглядеть следующим образом:

curl http://mydomain.com

А вот пример запроса POST:

curl –data “text=Hello” https://myDomain.com/firstPage.jsp

Здесь text=Hello — это параметр запроса POST. Такое поведение похоже на HTML-формы.

Вы также можете указать несколько методов HTTP в одной команде curl. Сделайте это, используя опцию –next, например:

curl –data “text=Hello” https://myDomain.com/firstPage.jsp —next https://myDomain.com/displayResult.jsp

Команда содержит запрос POST, за которым следует запрос GET.

Каждый HTTP-запрос содержит агент пользователя, который отправляется как часть запроса. Он указывает информацию о браузере клиента. По умолчанию запрос содержит curl и номер версии в качестве информации об агенте пользователя. Пример вывода показан ниже:

“GET / HTTP/1.1” 200 “_” ”curl/7/29/0”

Вы можете изменить дефолтную информацию об агенте пользователя, используя следующую команду:

curl -I http://mydomain.com –-user-agent “My new Browser”

Теперь вывод будет выглядеть так:

“GET / HTTP/1.1” 200 “_” ”My new Browser”

Forms explained

Forms are the general way a website can present a HTML page with fields for the user to enter data in, and then press some kind of ‘OK’ or ‘Submit’ button to get that data sent to the server. The server then typically uses the posted data to decide how to act. Like using the entered words to search in a database, or to add the info in a bug tracking system, display the entered address on a map or using the info as a login-prompt verifying that the user is allowed to see what it is about to see.

Of course there has to be some kind of program on the server end to receive the data you send. You cannot just invent something out of the air.

Location header

When a resource is requested from a server, the reply from the server may include a hint about where the browser should go next to find this page, or a new page keeping newly generated output. The header that tells the browser to redirect is .

Curl does not follow headers by default, but will simply display such pages in the same manner it displays all HTTP replies. It does however feature an option that will make it attempt to follow the pointers.

To tell curl to follow a Location:

If you use curl to POST to a site that immediately redirects you to another page, you can safely use () and / together. curl will only use POST in the first request, and then revert to GET in the following operations.

Simple Usage

Get the main page from a web-server:

Get the README file the user’s home directory at funet’s ftp-server:

Get a web page from a server using port 8000:

Get a directory listing of an FTP site:

Get the definition of curl from a dictionary:

Fetch two documents at once:

Get a file off an FTPS server:

or use the more appropriate FTPS way to get the same file:

Get a file from an SSH server using SFTP:

Get a file from an SSH server using SCP using a private key (not password-protected) to authenticate:

Get a file from an SSH server using SCP using a private key (password-protected) to authenticate:

Get the main page from an IPv6 web server:

Get a file from an SMB server:

6. Аутентификация

Аутентификация — передача серверу имени пользователя и пароля,
после этого он проверяет, имеете ли вы право выполнить требуемый
запрос. Аутентификация по методу Basic (которым curl пользуется по
умолчанию) основана на открытом тексте, что означает, что имя
пользователя и пароль не будут зашифрованы, а лишь слегка
«затуманены» по алгоритму Base64, что оставляет возможность
узнать эту информацию злоумышленникам на пути между вами и
HTTP-сервером.

Указание curl использовать имя пользователя и пароль:

        # curl -u name:password www.secrets.com

Сайт может требовать использования другого метода аутентификации
(посмотрите, что пишет сервер в заголовках), в этих случаях можно
использовать ключи —ntlm, —digest, —negotiate или даже —anyauth.
Иногда доступ к внешним HTTP-серверам происходит через прокси, так
часто делают в компаниях и фирмах. HTTP-прокси может требовать свои
логин и пароль для доступа к Интернету. Соответствующий ключ curl:

        # curl -U proxyuser:proxypassword curl.haxx.se

Если прокси требует аутентификации по методу NTLM, укажите
—proxy-ntlm, если метод Digest, то —proxy-digest.

Если вы не укажете пароль в ключах -u и -U, то curl спросит его у
вас в интерактивном режиме.

Заметьте, что когда curl работает, строка запуска (а вместе с этим
и ключи, и пароли) могут быть видны другим пользователям вашей
системы в списке задач. Есть способы предотвратить это. Об этом ниже.

Netrc

Unix introduced the concept a long time ago. It is a way for a user to specify name and password for commonly visited FTP sites in a file so that you don’t have to type them in each time you visit those sites. You realize this is a big security risk if someone else gets hold of your passwords, so therefore most unix programs won’t read this file unless it is only readable by yourself (curl doesn’t care though).

Curl supports files if told to (using the / and options). This is not restricted to just FTP, so curl can use it for all protocols where authentication is used.

A very simple file could look something like:

11.1 Сертификаты

В мире HTTPS для аутентификации в дополнение к имени
пользовавателя и паролю вы используете сертификаты. Curl поддерживает
сертификаты на стороне клиента. Все сертификаты заперты ключевой
фразой, которую вам нужно ввести прежде чем curl может начать с ними
работу. Ключевая фраза может быть указана либо в командной строке,
либо введена в интерактивном режиме. Сертификаты в curl используются
следующим образом:

        # curl -E mycert.pem https://that.secure.server.com

Curl также проверяет сервер на подлинность, сверяя сертификат сервера
с локально хранящимся. Обнаружившееся несоответствие приведет к тому,
что curl откажется соединяться. Для игнорирования проверки на
подлинность используйте ключ -k.

Более подробная информация о сертификатах может быть найдена на
странице .

Открыть только заголовок ответа

Если вы хотите быстро проверить заголовок ответа, то для этого можно использовать следующий синтаксис.

# curl --head http://yoururl.com

Пример:

# curl -I 74.125.68.100   
HTTP/1.1 200 OK   
Date: Sun, 18 Jan 2015 08:31:22 GMT   
Expires: -1   
Cache-Control: 
private, max-age=0   
Content-Type: text/html; charset=utf-8   
Set-Cookie: NID=67=SpnXKTDUhw7QGakIeLxmDSF; 
expires=Mon, 20-Jul-2015 08:31:22 GMT; path=/; domain=.; HttpOnly
P3P: CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for moreinfo."   
Server: gws   X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN   
Alternate-Protocol: 80:quic,p=0.02   
Transfer-Encoding: chunked
Accept-Ranges: none
Vary: Accept-Encoding
#

Отправка данных методом POST

Команда ниже отправляет POST запрос на сервер аналогично тому, как пользователь, заполнив HTML форму, нажал бы кнопку «Отправить». Данные будут отправлены в формате .

> curl -d "key1=value1&key2=value2" http://www.example.com
> curl --data "key1=value1&key2=value2" http://www.example.com

Параметр аналогичен , для отправки двоичных данных необходимо использовать параметр . Для URL-кодирования полей формы нужно использовать .

> curl --data-urlencode "name=Василий" --data-urlencode "surname=Пупкин" http://www.example.com

Если значение опции начинается с , то после него должно быть имя файла с данными (или дефис — тогда будут использованы данные из стандартного ввода). Пример получения данных из файла для отправки POST-запроса:

> curl --data @data.txt http://www.example.com

Содержимое файла :

key1=value1&key2=value2

Массив , который будет содержать данные этого запроса:

Array
(
     => value1
     => value2
)

Пример URL-кодирования данных из файла перед отправкой POST-запроса:

> curl --data-urlencode name@username.txt http://www.example.com

Содержимое файла :

Иванов Иван Иванович

Массив , который будет содержать данные этого запроса:

Array
(
     = Иванов Иван Иванович
)

Произвольные заголовки запроса

Возможно, вам понадобится изменять или добавлять элементы
отдельных запросов curl.

К примеру, вы можете изменить запрос POST на PROPFIND и отправить
данные как «Content-Type: text/xml» (вместо обычного
Content-Type):

        # curl -d "<xml>" -H "Content-Type: text/xml" -X PROPFIND url.com

Вы можете удалить какой-нибудь заголовок, указав его без содержимого.
Например, вы можете удалить заголовок ‘Host:’, тем самым сделав
запрос «пустым»:

        # curl -H "Host:" http://mysite.com

Также вы можете добавлять заголовки. Возможно, вашему серверу
потребуется заголовок ‘Destination:’:

        # curl -H "Destination: http://moo.com/nowhere" http://url.com

DESCRIPTION

curl is
a tool to transfer data from or to a server, using one of
the supported protocols (DICT, FILE, FTP, FTPS, GOPHER,
HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, MQTT, POP3, POP3S,
RTMP, RTMPS, RTSP, SCP, SFTP, SMB, SMBS, SMTP, SMTPS, TELNET
and TFTP). The command is designed to work without user
interaction.

curl offers a
busload of useful tricks like proxy support, user
authentication, FTP upload, HTTP post, SSL connections,
cookies, file transfer resume, Metalink, and more. As you
will see below, the number of features will make your head
spin!

curl is powered
by libcurl for all transfer-related features. See
libcurl(3) for details.

Предварительные сведения

Протокол HTTP

HTTP — это протокол, используемый при обмене данных между веб-сервером и программой-клиентом (например, браузером). Он состоит из строк ASCII-текста, отсылаемых от клиента к серверу для запроса какого-либо действия. При получении запроса сервер отвечает клиенту несколькими служебными текстовыми строками, а затем выдает запрошенное содержимое.

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

URL

URL (Uniform Resource Locator — единый указатель ресурса) задает адрес определенного ресурса в Интернет. Например, URL веб-страницы cURL, записывается так: .

Формы

Формы представляют собой наборы полей, размещенные на веб-странице. Пользователь вводит в эти поля данные, затем нажимает на кнопку «OK» или «Отправить», после чего данные отправляются на сервер. Сервер принимает данные и решает, как поступить дальше: искать ли информацию в базе данных, показать ли введенный адрес на карте или использовать информацию для аутентификации пользователя. Разумеется, «решает» — означает, что на стороне сервера должна быть какая-то программа, которая принимает и обрабатывает присланные данные. Простейший пример: форма запроса поисковика Google.

Справка

Справку по curl можно получить, набрав в командной строке

$ curl --help

или

$ curl --manual

— приглашение командной строки.

LDAP

If you have installed the OpenLDAP library, curl can take advantage of it and offer support. On Windows, curl will use WinLDAP from Platform SDK by default.

Default protocol version used by curl is LDAPv3. LDAPv2 will be used as fallback mechanism in case if LDAPv3 will fail to connect.

LDAP is a complex thing and writing an LDAP query is not an easy task. I do advise you to dig up the syntax description for that elsewhere. One such place might be: RFC 2255, The LDAP URL Format

If I want the same info in HTML format, I can get it by not using the (enforce ASCII) flag.

You also can use authentication when accessing LDAP catalog:

By default, if user and password provided, OpenLDAP/WinLDAP will use basic authentication. On Windows you can control this behavior by providing one of , or option in curl command line

On Windows, if no user/password specified, auto-negotiation mechanism will be used with current logon credentials (SSPI/SPNEGO).

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

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

Adblock
detector