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 и отображает статическое содержимое страницы. Оно аналогично тому, что мы видим при просмотре исходного кода в браузере.
cURL POST command line on WINDOWS RESTful service
My problem: Using the command line tool to curl my localhost server while sending some data along with my POST request is not working.
What seems to be causing the error: Imagine something like this
Result of the returning data
After some searching i figured out that problem couldn’t be the sintax used for the request since it works on UNIX shells.
Are you possibly using Windows? That so looks like a completely broken shell that doesn’t properly deal with single-quotes vs double-quotes. I just tried that command line and it worked fine on my linux box. http://curl.haxx.se/mail/archive-2011-03/0066.html
I tried to work around with those » escaping it \» but it still didn’t work
So i gave up. Windows seems to messing up with the JSON object sent on POST
7 Answers 7
I ran into the same issue on my win7 x64 laptop and was able to get it working using the curl release that is labeled Win64 — Generic w SSL by using the very similar command line format:
Which only differs from your 2nd escape version by using double-quotes around the escaped ones and the header parameter value. Definitely prefer the linux shell syntax more.
Another Alternative for the command line that is easier than fighting with quotation marks is to put the json into a file, and use the @ prefix of curl parameters, e.g. with the following in json.txt:
then in my case I issue:
Keeps the json more readable too.
Alternative solution: A More Userfriendly solution than command line:
If you are looking for a user friendly way to send and request data using HTTP Methods other than simple GET’s probably you are looking for a chrome extention just like this one http://goo.gl/rVW22f called AVANCED REST CLIENT
For guys looking to stay with command-line i recommend cygwin:
I ended up installing cygwin with CURL which allow us to Get that Linux feeling — on Windows!
Using Cygwin command line this issues have stopped and most important, the request syntax used on 1. worked fine.
Useful links:
I hope it helps someone because i spent all morning on this.
Как сделать POST-запрос с помощью cURL
Главное меню » Linux » Как сделать POST-запрос с помощью cURL
cURL используется разработчиками для тестирования API, просмотра заголовков ответов и выполнения HTTP-запросов.
В этой статье мы собираемся объяснить, как использовать cURL для выполнения запросов POST. Метод HTTP POST используется для отправки данных на удаленный сервер.
Создание POST-запроса
Общая форма команды curl для выполнения запроса POST выглядит следующим образом:
Тип тела запроса указывается его заголовком Content-Type.
Обычно запрос POST отправляется через форму HTML. Данные, отправляемые в форму, обычно закодированы в виде multipart/form-data или типе содержимого application/x-www-form-urlencoded.
Чтобы создать запрос POST, используйте параметр -F, а затем пару field=value. В следующем примере показано, как сделать POST-запрос к форме с полями «name» и «email»:
Когда опция -F используется, curl отправляет данные, используя multipart/form-dataContent-Type.
Другой способ сделать запрос POST – использовать опцию -d. Это приводит curl к отправке данных с использованием application/x-www-form-urlencodedContent-Type.
Если опция -d используется более одного раза, вы можете объединить данные, используя символ &:
Указание типа контента
Чтобы установить определенный заголовок или тип содержимого, используйте параметр -H. Следующая команда устанавливает тип запроса POST application/json и отправляет объект JSON:
Загрузка файлов
Чтобы POST файл с curl, просто добавьте символ @ перед местоположением файла. Файл может быть архивом, изображением, документом и т. д.
Вывод
Мы показали вам, как использовать curl для выполнения запросов POST. Для получения дополнительной информации curl посетите страницу 5 примеров использования команды Curl.
Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.
Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.
How to make a Curl POST call in Windows?
I am trying to issue the following command under Windows 10:
Unfortunately, it produces numerous errors:
Apparently, it does not understand the syntax.
Why is this, and how can this be fixed?
5 Answers 5
Another option is to mask doublequotes with backslash like this:
It looks like you’re using cmd.exe . Command Prompt’s character escaping rules are both archaic and awful. I recommend using Powershell instead; it uses rules much more similar to those of bash on other *nix shells (though not identical, notably because it uses ` (backtick) as the escape character instead of backslash).
Here’s the command in Powershell on my system:
The leading & is required because the path to the program is a quoted string. I had to specify the path because I don’t have a curl.exe in my Windows PATH . However, I could just escape the space in «Program Files»:
Single and double quotes otherwise work as you’re using them, with the ‘ delimiting the start of a string and the » appearing just as literal characters inside it.
Note that you do have to provide the path to a curl executable, or at least specify curl.exe ; curl by itself is a Powershell alias for the Invoke-WebRequest cmdlet, which can do most of what the cURL program can do but has very different argument syntax.
Also, while you can invoke Powershell from cmd using powershell -c , that wouldn’t really help here because you’d have to escape the string using cmd ‘s silly syntax anyhow.