Curl is a command line tool for sending client requests. Curl curl curl Curl Curl curl curl curl curl curl curl The biggest advantage of curl is that it can be sent at any time. For example, there are many scenarios where we just want to quickly validate a request or interface:

Send a GET request directly from the command line
curl https://xxx.com/api/v1/xxx

Send a POST request
curl -X POST -d "k1=123&k2=456" https://xxx.com/api/v1/xxx
Copy the code

The curl is installed

To install curl, go to the curl website and download the correct version of curl. After installing curl, you need to configure environment variables.

After the installation, restart the terminal and check the version
curl -V
Copy the code

If you can see the following information, the installation is successful:

Send a GET request

  • curlYou can access it by adding the URLGETrequest
curl https://www.baidu.com
Copy the code

Request baidu url effect is as follows:

  • sendGETThe request carries the request parameters
curl https://www.xxx.com/?key=value1&key2=value2
Copy the code

A POST request

-x POST –data “k1=v1&k2=v2” Sends the POST request with the request data. CURL CURL CURL CURL CURL CURL CURL CURL CURL CURL CURL CURL CURL

/** * HTTP service that processes POST requests and returns POST data */
const http = require('http');

const server = http.createServer((req, res) = > {
  if (req.method === 'POST' && hasbody(req)) {
    const buffer = [];
    req.on('data'.(chunk) = > {
      buffer.push(chunk);
    });
    req.on('end'.() = > {
      const rawBody = Buffer.concat(buffer).toString();
      res.writeHead(200);
      res.end(rawBody);
    });
  } else {
    res.end(' '); }}); server.listen(3000.() = > {
  console.log('server running at port 3000.');
});

// Determine if body requests entity data
function hasbody (req) {
  return req.headers['transfer-encoding']! = =undefined ||
    !isNaN(req.headers['content-length']);
}
Copy the code

Curl sends a POST request:

curl -X POST --data "key1=123&key2=456" http://localhost:3000

# --data can be shortened to -d
curl -X POST -d "key1=123&key2=456" http://localhost:3000
Copy the code

  • rightpostdataurlcoding
--data-urlencode is not -d
# --data的简写是-d
curl --data-urlencode "k1=1&k2=a b"  http://localhost:3000
Copy the code

For example, if there is a space between a and b, use –data-urlencode to encodeURIComponent it:

Send a HEAD request

const http = require('http');

const server = http.createServer((req, res) = > {
  res.writeHead(200);
  res.end();
});

server.listen(3000.() = > {
  console.log('server running at port 3000.');
});
Copy the code

The -i argument can send a HEAD request:

curl -I http://localhost:3000
Copy the code

Send a DELETE request

The -x DELETE argument can send DELETE requests:

curl -X DELETE http://localhost:3000
Copy the code

Send a PUT request

Here is a very simple Node service to save images uploaded by users as images:

const http = require('http');
const fs = require('fs');

const server = http.createServer((req, res) = > {
  // If a PUT request is made and the interface accessed is /upload/file
  if (req.method === 'PUT' && req.url === '/upload/file') {
    // Save the user's data as a static/mime.png image
    const writeStream = fs.createWriteStream(__dirname + '/static/mime.png');
    req.pipe(writeStream).on('finish'.() = > {
      res.writeHead(200);
      res.end('upload success');
    });
    writeStream.on('error'.(err) = > {
      res.writeHead(500);
      res.end('server error.'); }); }}); server.listen(3000.() = > {
  console.log('server running at port 3000.');
});
Copy the code

Using curl, you can send a PUT request to curl.

curl -T ./mime.png http://localhost:3000/upload/file
Copy the code

At the end of the request, you can see that the uploaded image has been saved:

Curl download file

Download save file is to add -o save address parameter.

Download baidu HTML file locally
curl -o ./my-download.html https://www.baidu.com
Copy the code

The curl command looks like this, and the file has been downloaded:

View the response header parameters

The -i parameter returns the response header

curl -i  https://www.baidu.com
Copy the code

View complete packet information

  • -vParameter Displays complete packet information
curl -v https://www.baidu.com
Copy the code

  • --trace ./log.txtView more detailed information and write the data to the specified file.
curl --trace ./log.txt https://www.baidu.com
Copy the code

  • --trace-ascii ./log.txtView more detailed information in ASCII encoding and write the data to the specified file.

Specify the user-agent for the request

We start a simple HTTP service and configure vscode debug to see what curl sends:

const http = require('http');

const server = http.createServer((req, res) = > {
  // Set a breakpoint here to view the reQ request object
  res.end(' ');
});

server.listen(3000.() = > {
  console.log('server running at port 3000.');
});
Copy the code

Curl curl curl curl curl curl curl curl curl curl curl curl

User-agent for Chrome is Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.109 Safari/537.36

–user-agent “XXX” can specify the user-agent to send the request. The parameter is abbreviated as -a:

curl --user-agent "Mozilla / 5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.109 Safari/537.36" http://localhost:3000

# --user-agent -A
curl -A "Mozilla / 5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.109 Safari/537.36" http://localhost:3000
Copy the code

Specifies the jump to the request

Referer Indicates the url before the forward redirect

curl --referer http://localhost:3000 http://localhost:3000/newpath
Copy the code

Send request at this time of the req. The url is the new address, http://localhost:3000/newpath, and carry the referer field in headers.

Cookie parameters are carried with the request

  • --cookie "k1=v1&k2=v2"carrycookieParameters,--cookieI can write it as theta-b:
curl --cookie "k=1&k2=2" http://localhost:3000

# --cookie -b
curl -b "k=1&k2=2" http://localhost:3000
Copy the code

  • curlSave the servercookieGo to the specified file

In order to use curl to carry the cookie set by the server, you can first save the cookie set by the server and then carry the cookie set by the server. Here is an example of a node setting a cookie:

const http = require('http');

const server = http.createServer((req, res) = > {
  // Node sets the cookie
  res.writeHead(200, {
    'Set-Cookie': 'key1=value1&key2=value2'}); res.end('cookie set success.');
});

server.listen(3000.() = > {
  console.log('server running at port 3000.');
});
Copy the code

Curl curl curl curl curl curl curl curl curl curl curl curl -c path/to/save

curl -c ./cookie http://localhost:3000
Copy the code

  • curlCarried when sending the requestcookiefile
curl -b ./cookie http://localhost:3000
Copy the code

Now debug can see that reQ already carries our cookie:

reference

  • The curl document
  • Curl Website development guide Ruan Yifeng
  • Ruan Yifeng

conclusion

Curl is a handy tool for quickly verifying a service, and it gets better and better every time you use it. I hope you can use it after reading this tutorial to help you with your daily development work.

I am your old friend Leng Hammer, who like this article ❤️❤️❤️, please move your little finger to praise ha, 👍 ❤️❤️!! Your support is my motivation, come on, Ollie!!