Curl example in windows

Утилита командной строки CURL

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

Для начала скачаем саму утилиту, для этого переходим на официальный сайт утилиты, в раздел Download. После скачивания архива для своей платформы (у меня это Windows 64 bit), распаковываем архив. Чтобы иметь возможность работать с HTTPS и FTPS, устанавливаем сертификат безопасности url-ca-bundle.crt , который находится в папке curl/bin .

Запускаем командную строку, переходим в директорию curl/bin и пытаемся скачать главную страницу Google:

Опция -X позволяет задать тип HTTP-запроса вместо используемого по умолчанию GET. Дополнительные запросы могут быть POST, PUT и DELETE или связанные с WebDAV — PROPFIND, COPY, MOVE и т.п.

Следовать за редиректами

Сервер Google сообщил нам, что страница google.com перемещена (301 Moved Permanently), и теперь надо запрашивать страницу www.google.com . С помощью опции -L укажем CURL следовать редиректам:

Сохранить вывод в файл

Чтобы сохранить вывод в файл, надо использовать опции -o или -O :

  • -o ( o нижнего регистра) — результат будет сохранён в файле, заданном в командной строке;
  • -O ( O верхнего регистра) — имя файла будет взято из URL и будет использовано для сохранения полученных данных.

Сохраняем страницу Google в файл google.html :

Сохраняем документ gettext.html в файл gettext.html :

Загрузить файл, только если он изменён

Опция -z позволяет получить файлы, только если они были изменены после определённого времени. Это будет работать и для FTP и для HTTP. Например, файл archive.zip будет получен, если он изменялся после 20 августа 2018 года:

Команда ниже загрузит файл archive.zip , если он изменялся до 20 августа 2018 года:

Прохождение аутентификации HTTP

Опция -u позволяет указать данные пользователя (имя и пароль) для прохождения базовой аутентификаци (Basic HTTP Authentication):

Cookie используются сайтами для хранения некой информации на стороне пользователя. Сервер сохраняет cookie на стороне клиента (т.е. в браузере), отправляя заголовки:

А браузер, в свою очередь, отправляет полученные cookie обратно на сервер при каждом запросе. Разумеется, тоже в заголовках:

Передать cookie на сервер, как будто они были ранее получены от сервера:

Чтобы сохранить полученные сookie в файл:

Затем можно отправить сохраненные в файле cookie обратно:

Файл cookie.txt имеет вид:

Получение и отправка заголовков

По умолчанию, заголовки ответа сервера не показываются. Но это можно исправить:

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

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

  • Строка, начинающаяся с > означает заголовок, отправленный серверу
  • Строка, начинающаяся с означает заголовок, полученный от сервера
  • Строка, начинающаяся с * означает дополнительные данные от CURL

А вот так можно отправить свой заголовок:

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

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

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

Читайте также:  Windows 10 full system backup

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

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

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

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

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

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

Загрузка файлов методом POST

Для HTTP запроса типа POST существует два варианта передачи полей из HTML форм, а именно, используя алгоритм application/x-www-form-urlencoded и multipart/form-data . Алгоритм первого типа создавался давным-давно, когда в языке HTML еще не предусматривали возможность передачи файлов через HTML формы.

Со временем возникла необходимость через формы отсылать еще и файлы. Тогда консорциум W3C взялся за доработку формата POST запроса, в результате чего появился документ RFC 1867. Форма, которая позволяет пользователю загрузить файл, используя алгоритм multipart/form-data , выглядит примерно так:

Чтобы отправить на сервер данные такой формы:

Скрипт upload.php , который принимает данные формы:

Работа по протоколу FTP

Скачать файл с FTP-сервера:

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

10 команд curl, которые вам следует знать

Команда Mail.ru Cloud Solutions перевела статью, автор которой составил краткий справочник часто используемых команд curl для протоколов HTTP/HTTPS. Это не замена официального руководства по cURL, скорее, краткий конспект.

cURL (расшифровывается как Client URL) — программное обеспечение, которое предоставляет библиотеку libcurl и инструмент командной строки curl. Возможности cURL огромны, во многих опциях легко потеряться.

curl — инструмент для передачи данных с сервера или на него, при этом используется один из поддерживаемых протоколов: DICT, FILE, FTP, FTPS, GOPHER, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMB, SMBS, SMTP, SMTPS, TELNET и TFTP. Команда предназначена для работы без взаимодействия с пользователем.

Команда curl запускается из командной строки и предустановлена в большинстве дистрибутивов Linux.

  • доступ без браузера;
  • внутри shell-скриптов;
  • для тестирования API.

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

Если никакие аргументы не указаны, то команда curl выполняет HTTP-запрос get и отображает статическое содержимое страницы. Оно аналогично тому, что мы видим при просмотре исходного кода в браузере.

Installing and using cURL

All the examples in the Zendesk REST API docs use cURL, a lightweight, command-line tool for making HTTP requests without a web browser. cURL lets you try out various API requests in a command-line interface such as the command prompt in Windows or Terminal in macOS. You don’t need to build a working web application just to try out the APIs.

cURL makes HTTP requests just like a web browser. To request a web page from the command line, type curl followed by the site’s URL:

The web server’s response is displayed directly in your command-line interface. If you requested an HTML page, you get the page source — which is what a browser normally sees.

This article covers the following topics:

Using cURL

You can use cURL to inspect and test different Zendesk API requests without having to build a functioning web application. For example, the following cURL statement makes an HTTP request to the List Groups endpoint in the Zendesk API:

The API returns a JSON object that lists the groups in your Zendesk Support instance:

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It’s designed to be easy for humans to read and write, and for machines to parse and generate. To learn more, see Working with JSON.

Читайте также:  Dns сервер не найден windows

Using cURL in Windows

You can use the Windows command prompt to run the cURL examples. To start the command prompt, open the Start menu, type cmd in the search box, and press Enter.

cURL isn’t installed in Windows by default. See Installing cURL below to install it on your system.

The examples in the docs have to be modified slightly to work correctly in Windows. First, replace any line-ending backslash (\) character with the caret (^) character. Second, if an example contains JSON data, move the data to a file before running the example. The following sections give more details.

Replace line-ending backslashes

The cURL examples often have a backslash (\) at the end of lines to break up a long statement into easier-to-read lines. The backslash is a line continuation character in UNIX but not in Windows. In Windows, replace any backslash at the end of lines with the caret (^) character, which is an escape character in Windows. Don’t leave any space after any ^ character or it won’t work. The caret will escape the space instead of the new line.

You can paste a multiline statement at the command prompt by clicking the icon in the upper-left corner and selecting Edit > Paste. If you prefer using the keyboard, press Alt+spacebar to open the menu, then press E and P.

Move JSON data to a file

The Windows command prompt doesn’t support single quotes. It’s a problem because cURL statements use single quotes to specify JSON data. Example:

The statement specifies JSON data for creating a group (the -d flag stands for data). Because the JSON is enclosed in single quotes, the statement won’t work on the command line.

To fix the problem, save the JSON in a separate file and import it into the cURL statement. To modify the example above, create a file named json.txt containing the following text:

Next, change the cURL statement to import the JSON data with the @filename syntax:

Before running the statement, use the cd command (for change directory) to navigate to the folder that contains the file. Example:

C:\> cd json_files

Then paste the cURL statement at the command prompt:

An alternative to moving the JSON to a separate file is to use double quotes around the JSON data in the cURL statement and escape the inner ones with backslashes:

It doesn’t end there. The following special characters in strings must be escaped with the caret (^) character: &, \, , ^, | . If the JSON includes HTML, such as when you try to create or update an article in Help Center, you need to find and escape all the angle brackets in the HTML.

This is tedious and error prone. Best to stick with importing the JSON from a file.

Installing cURL

macOS

cURL is installed by default on macOS. To try it out, see Testing your cURL installation below.

Windows 10, version 1803 or later

If you have version 1803 or later of Windows 10, cURL is installed by default. To try it out, see Testing your cURL installation below.

Windows

If you have a version of Windows earlier than Windows 10, version 1803, you can download and install cURL as follows.

In Windows, create a new folder called curl in your C: drive.

Go to http://curl.haxx.se/download.html and download one of the following zip files:

  • If you have a Windows 64 system, scroll to the Win64 — Generic section and look for the latest Win64 ia64 zip version with SSL support. It’s normally second in the list. Click the version number to start the download.
  • If you have a Windows 32 system, scroll to the Win32 — Generic section and look for the latest Win32 zip version with SSL support. It’s normally second in the list. Click the version number to start the download.
Читайте также:  Как отключить выравнивание по сетке windows 10

Unzip the downloaded file and move the curl.exe file to your C:\curl folder.

Go to http://curl.haxx.se/docs/caextract.html and download the digital certificate file named cacert.pem.

The PEM file contains a bundle of valid digital certificates. The certificates are used to verify the authenticity of secure websites. They’re distributed by certificate authority (CA) companies such as GlobalSign and VeriSign. The PEM file allows cURL to connect securely to the Zendesk API using the Secure Sockets Layer (SSL) protocol.

Move the cacert.pem file to your C:\curl folder and rename it curl-ca-bundle.crt.

Add the curl folder path to your Windows PATH environment variable so that the curl command is available from any location at the command prompt. Update the variable as follows:

In the Start menu, right-click This PC and select More > Properties.

Note: In Windows 7, right-click Computer and select Properties.

Click Advanced System Settings.

In the Advanced tab, click the Environment Variables button on the lower right side.

Select the «Path» variable in System Variables, and click Edit.

In the Edit environment variable dialog box, click New and add the path to the curl.exe file. Example: C:\curl.

Windows 7: In the Variable Value textbox, append a semicolon to the value, followed by the path to the curl.exe file. Example: ;C:\curl

Keep clicking OK to accept the change and close the dialog box.

Testing your cURL installation

You can test your cURL installation by making a request to the Zendesk API. The test retrieves your Zendesk Support user information.

To test cURL

Paste the following cURL statement into your favorite text editor:

For details on this endpoint, see Show the Currently Authenticated User in the Zendesk API docs.

Replace the placeholders in curly brackets with the information you use to sign in to Zendesk Support. Example:

Launch your command-line interface.

  • In Windows, open the Start menu, type cmd in the search box, and press Enter.
  • In macOS, double-click the Terminal application in your Applications/Utilities folder.

Copy the cURL statement from your text file and paste it at the command prompt.

Windows users: After copying it to the Clipboard, select Edit > Paste from the context menu in the upper left corner of the window:

Press Enter to run the cURL statement.

The console should display your Zendesk Support user information formatted as a JSON object.

You can pretty print the results to make it easier to read. See Converting JSON to data you can understand.

Common cURL flags

You’ll see the following cURL flags in the examples in the Zendesk REST API docs.

-H

Specifies any extra header content to include in the HTTP request. API requests that submit data to our servers typically include the data’s content type. Example:

Example: -H «Content-Type: application/json» .

-u

Specifies the user name and password to use for server authentication. The user name and password are separated by a colon.

Example: -u myemail@example.com:mypassword

-v

Makes the response more verbose.

-X

Specifies the request method to use when communicating with the HTTP server. Example: PUT or POST .

-G —data-urlencode

Used for API endpoints that send data in a query string, such as the Search API. The —data-urlencode option url-encodes the query string. The -G flag specifies that the url-encoded data is for a GET request rather than a POST request.

For example, suppose you want to run the following search using the List Search Results endpoint:

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