Make post request from linux

Как сделать POST-запрос с помощью cURL

cURL — это утилита командной строки для передачи данных с или на удаленный сервер с использованием одного из поддерживаемых протоколов. Он установлен по умолчанию в macOS и большинстве дистрибутивов Linux.

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-запрос в форму с полями «имя» и «электронная почта»:

Когда используется опция -F , curl отправляет данные с использованием Content-Type multipart/form-data .

Другой способ сделать запрос POST — использовать параметр -d . Это заставляет curl отправлять данные с использованием Content-Type application/x-www-form-urlencoded Content-Type.

Если параметр -d используется более одного раза, вы можете объединить данные с помощью символа & :

Указание Content-Type

Чтобы установить определенный заголовок или Content-Type, используйте параметр -H . Следующая команда устанавливает тип запроса POST на application/json и отправляет объект JSON:

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

Чтобы отправить файл с помощью curl , просто добавьте символ @ перед местоположением файла. Файл может быть архивом, изображением, документом и т. Д.

Выводы

Мы показали вам, как использовать curl для выполнения запросов POST. Дополнительные сведения о curl см. На странице документации по Curl .

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.

Источник

How to send HTTP request using curl and wget command from Linux and UNIX? Example Tutorial

You can use either curl or wget command to send HTTP requests from UNIX or Linux operating system. Both commands allow you to send GET and POST requests, which means you can also call REST web services. I have a Java web application, which runs on Linux and exposes WebServices. I was writing a UNIX script to download In some data from that web service when I hit by the question, how do I make an HTTP call from UNIX? What is the UNIX command should I use? If you are also facing the same problem, then you have come to the right ht place. Basically, you can use two UNIX commands to make the HTTP request, wget , and curl .

You can use curl and wget to send both GET and POST HTTP requests. My use case was rather simple, I just need to make a GET call to web service to download the data, but these two commands are mighty and provide many different options to interact with the web using HTTP right from the shell.

Between wget and curl (also known as cURL), curl (I call it «karl») is my favorite. Why? I think because I have used it more often than wget :-).

You can make your choices if you have good knowledge of the Linux command line, and that’s why I suggest every programmer and software developer join Learn Linux in 5 Days and Level Up Your Career course on Udemy, the best way to become efficient in Linux.

Читайте также:  Acer one 10 n15p2 драйвера windows 10

Now let’s see how to send HTTP requests from UNIX using the curl command.

Linux Command to send HTTP GET request

Here is one example of calling web service from Linux shell by sending HTTP GET request using cURL command:

You can also specify timeout using — m option as shown below:

This request will timeout in 2 seconds if it doesn’t receive any response.

You can also use wget to send HTTP requests and download the data. The only difference between curl and wget is that curl will print output in console and wget will store it in the file e.g.

will download the content of index.html and store it into a file with the same name.

Here is how you can use curl to download wget command in UNIX:

UNIX command to Send an HTTP POST request

You can also use curl to send HTTP post requests. All you need to do is use the —data option to specify the data you want to POST to web service e.g.

if you want to send data from file to web service, you can also use the following command:

Similarly, if you’re going to upload a file, you can do so by executing the following command:

Btw, these are just the tip of the iceberg when it comes to seeing the real power of curl command. If you want to learn more, I suggest you check out the Linux Command Line Basics course on Udemy. One of the best courses to learn basic and advanced Linux commands.

That’s all about how to send HTTP requests from UNIX and Linux. It’s simple, just remember the curl and wget command. You can explore their option by using man wget and man curl. Also, remember the difference between curl and wget, the former prints the output in the console while the later store the response in the same file as requested. I personally like curl because it’s easier to use but if you like wget stick with it.


Related UNIX Command Tutorials
If you are a Java developer often working in a Linux or UNIX environment then you will also find the following tutorials useful:

  • 10 examples of find command in UNIX (examples)
  • 10 examples of grep command in UNIX (examples)
  • 10 examples of date command in Linux (examples)
  • How to get an IP address from the hostname and vice-versa in Linux (command)
  • 10 examples of xargs command in Linux (examples)
  • 10 Courses to learn Linux commands for beginners (best courses)
  • 10 examples of tar command in UNIX (examples)
  • 10 examples of Vim in UNIX (examples)
  • How to create, update and delete soft link in UNIX (command)
  • How to delete empty files and directory in UNIX (solution)
  • How to make a directory tree in one command? (example)
  • How to how long argument of a process in Solaris (command)
  • UNIX command to find out how long a process is running? (answer)
  • UNIX command to find the size of the file and directory? (command)
  • 5 examples of sort command in Linux (examples)
  • 5 examples of kill command in Linux (examples)
  • 10 examples of chmod command in UNIX (examples)
  • 10 tips for working fast in UNIX? (tips)

Thanks for reading this article so far. If you like this article, then please share it with your friends and colleagues. If you have any questions or feedback, then please drop a note.

P. S. — If you want to learn Linux and looking for some free resources like books and online courses, then you can also check out this list of free Linux courses for Programmers and IT Professionals. This list contains some of the best free courses from Udemy, Pluralsight, Coursera, Codecademy, and other online platforms.

Читайте также:  Linux mint cinnamon установка рядом с windows

Источник

How to Perform a POST Request Using Curl

With diverse levels of information, we can make the post queries. Some test queries for POST are given below:

Making a simple POST request

Enter the following command on the command-line to make an easy POST request through curl.

Sending additional fields with a POST request

You can send additional fields with the help of the -d flag and coupling it with the POST request you send to the server. The following POST call sends a user and a transfer area together with the critical parameters.

The -d option to POST with curl will provide a standard header that looks like:

Specifying the Content-Type in POST request

You can use the -H flag to send a piece of data or a header with a curl. The command that follows sends a JSON object with a request.

Exchanging files with CURL

Using curl, we can also transfer entire files on the command line. Although, in this case, it won’t upload any data as the site we are accessing is not found. To do this, the command is shown as:

Conclusion

This article shows the importance of the Curl command in Linux and discusses the usage of curl post requests on Linux. I clarified how to make POST requests using the CURL command.

About the author

Younis Said

I am a freelancing software project developer, a software engineering graduate and a content writer. I love working with Linux and open-source software.

Источник

How to Use cURL Post Data from File

cURL is a free and open-source command-line utility used for transferring data to or from a remote host with minimal user interaction. cURL works with primary protocols like HTTP, FTP, SCP, and SFTP.

It allows users to upload and download data either using single commands or bash scripts. It also provides features such as user-authentication, proxy tunneling, download resume, form-based uploads, SSL certificates, and so much more. It is safe to say that cURL is more than an HTTP client.

This tutorial will walk you through one cURL functionality that allows users to perform HTTP post requests using file data.

Before we get started, let me mention that this is not a beginner’s guide to cURL; you need a degree of prior know-how, especially knowledge of network protocols, HTTP requests, and more.

Before we can dive into using cURL to carry out POST requests, let us first get setup.

How to Install cURL

In most cases, you will find cURL installed in major Linux distributions by default. To confirm you have cURL, use the command

If you get an error:

You will need to install it before proceeding.

Use the default package manager to complete the installation as shown in the commands below:

sudo apt-get update

sudo apt-get install curl -y

Before discussing how to POST data from a file with cURL, allow me to talk about the POST request in brief. As usual, if you are already familiar with this, you can feel free to skip ahead; otherwise, stick around.

cURL POST Request

The HTTP post request is one of the most popular HTTP/HTTPS request methods used to send data to a remote host to create or update a resource.

Now:

Please do not confuse the method with PUT; although they’re quite similar, they have their differences.

The data sent using a POST request is mainly stored in the request body of the HTTP request.

For example, consider the below POST request that sends username and password as well as their values.

To send the above POST request using cURL, we can specify the commands as:

In the above command, we used the -d option to tell cURL to include the default headers, which is Content-Type: application/x-www-form-urlencoded

Читайте также:  Файл iso windows чтобы установить с флешки

The -X option specifies the HTTP request method to use, in this case, HTTP POST request.

cURL Specify Content-Type

In some cases, we might want to specify [explicitly] the Content-Type when sending the request. The Content-Type entity in the header specifies the type of media of the resource we are sending. The media type is also commonly known as the MIME Type.

If you wish to learn about MIME Types, consider the resource provided below:

To specify the Content-Type in a cURL request, we can use the -H flag. For example, let us send MIME Type of application/JSON.

The above specifies that we want to send a JSON object to the provided URL. You can use this to read the values from a JSON file or send it as raw.

How to Read Data from a File

Suppose you want to make requests in the command-line using cURL, but you have the data to send stored in a file. You can use the Content-Type to specify the media type and then pass the file path containing the data. For this example, I will illustrate using a JSON object.

The JSON file (data.json) contains the following values:

To send this data from a JSON file, we can use the -d and then pass the filename as shown in the command below:

You can also use the –data-binary option.

You can also use a text file to send the data; all you need to specify is the Content-Type as text/plain.

For example, a text file (data.txt) containing the following values

Using the cURL command, simply send the request as:

You can use other file types you can use such as XML, HTML, and many more.

Conclusion

In this tutorial, we have discussed how to make POST requests and pass data in various formats. It is good to keep in mind that besides being very powerful, cURL is also very flexible. It can combine a collection of options in a single command to create powerful requests. For more information, I recommend the cURL documentation as it is well written.

Thank you for reading, and have fun with cURL.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list

Источник

How to cURL POST from the Command Line

Curl is the powerful command line utility that allows you to transfer data to or from a server or URL. One common function used by developers is to make a POST request with curl, which is what we’re going to cover here.

We’ll keep things fairly simple and show three examples to make a POST request with curl from the command line, with syntax with and without data, and also to a form.

cURL POST Request Command Line Syntax

You can make a curl POST request with or without data, depending on what you’re attempting to do. Remember that using proper syntax capitalization matters.

curl post request with no data:

curl -X POST http://URL/example.php

curl post request with data:

curl -d «data=example1&data2=example2» http://URL/example.cgi

curl POST to a form:

curl -X POST -F «name=user» -F «password=test» http://URL/example.php

curl POST with a file:

curl -X POST -F «image=@/path/example.gif» http://URL/uploadform.cgi

Similarly, you can also download files with curl too by using a different command string.

curl POST JSON data

curl -H «Content-Type: application/json» -X POST -d ‘<"user":"bob","pass":"123">‘ http://URL/

For further curl specifics or details, refer to the curl manual or help page:

Know of a better way to make a post request with cURL? Let us know in the comments. You can also check out some interesting specific uses of the curl command here.

Источник

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