curl的使用

curl的使用

curl是常用发起http请求工具,今天就整理下如何正确的使用curl命令,来提高工作效率。

首先我们使用curl --help命令来看下官方的使用介绍:

curl的使用

可以看到curl的命令格式为:curl [option] \<url\>

  1. 直接访问网页

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
         $ curl http://www.baidu.com
    ```

    2. 访问的数据存成文件

    ``` bash
    $ curl http://www.baidu.com >>baidu.html
    ```

    ``` bash
    $ curl -o baidu.com http://www.baidu.com
    ```


    -O 可以使用默认名称存储,可以直接保存。

    ``` bash
    curl -O https://www.baidu.com/img/baidu_jgylogo3.gif

    直接下载图片成baidu_jgylogo3.gif

  1. 发送POST,DELETE,PUT的方法,发送自定义命令,需要使用-X这个参数。post,put ,delete 请求发送  

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
         curl -X POST http://localhost:8080/index
    curl -X PUT http://localhost:8080/index
    curl -X DELETE http://localhost:8080/index
    ```
            
    4. 增加请求参数

    在请求一个网址网址的时候,常常需要加上对应的请求参数,这里需要增加一个-d的参数

    ``` bash
    curl -X POST -d '{"userName":"fuwei","blog":"blog.laofu.online"}' http://localhost:8080/index
    ```

    5. 增加请求头信息    
      
      curl修改header信息,需要-H参数:

    ``` bash
    curl -X POST -H 'Content-type: application/json' -d '{"userName":"fuwei","blog":"blog.laofu.online"}' http://localhost:8080/index
    ```

    6. 使用代理  

    ``` bash
    curl -x 192.168.0.112:8080 http://localhost:8080/index
  2. 保存Cooike和响应数据
 
1
curl -c cookiec.txt  http://localhost:8080/index
或者只用-D把响应的头存入文件中。
1
curl -D cookiec.txt  http://localhost:8080/index  
  1. 使用Cookie      

    1
    curl -b cookiec.txt http://localhost:8080/index
  1. 使用User-Agent的属性 

    1
    curl -A "iphone" http://localhost:8080/index
  2. Refer属性的添加 

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
         curl -e "www.baidu.com" http://localhost:8080/index
    ```

    11. 下载文件     

    11.1 单个下载

    单个下载可以使用"-o fileName" 或者-O(默认的名称)来保存文件    
    ``` bash
    curl -O https://www.baidu.com/img/baidu_jgylogo3.gif
 11.2 批量下载     

   批量下载jpg1-5

 
1
2
3
4
5
6
7
8
 curl -O https://www.baidu.com/jpg[1-5].JPG
```


11.3 断点续传

``` bash
curl -C -O https://www.baidu.com/jpg1.JPG
作者

付威

发布于

2019-02-07

更新于

2020-08-10

许可协议

评论