How can I set the request header for curl?
How would I pass multiple values in the header for a开发者_运维百科 curl
request?
Just use the -H
parameter several times:
curl -H "Accept-Charset: utf-8" -H "Content-Type: application/x-www-form-urlencoded" http://www.some-domain.example
To pass multiple headers in a curl request you simply add additional -H
or --header
to your curl command.
Example
//Simplified
$ curl -v -H 'header1:val' -H 'header2:val' URL
//Explanatory
$ curl -v -H 'Connection: keep-alive' -H 'Content-Type: application/json' https://www.example.com
Going Further
For standard HTTP header fields such as User-Agent, Cookie, Host, there is actually another way to setting them. The curl command offers designated options for setting these header fields:
- -A (or --user-agent): set "User-Agent" field.
- -b (or --cookie): set "Cookie" field.
- -e (or --referer): set "Referer" field.
- -H (or --header): set "Header" field
For example, the following two commands are equivalent. Both of them change "User-Agent" string in the HTTP header.
$ curl -v -H "Content-Type: application/json" -H "User-Agent: UserAgentString" https://www.example.com
$ curl -v -H "Content-Type: application/json" -A "UserAgentString" https://www.example.com
Sometimes changing the header is not enough, some sites check the referer as well:
curl -v \
-H 'Host: restapi.some-site.com' \
-H 'Connection: keep-alive' \
-H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' \
-H 'Accept-Language: en-GB,en-US;q=0.8,en;q=0.6' \
-e localhost \
-A 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.65 Safari/537.36' \
'http://restapi.some-site.com/getsomething?argument=value&argument2=value'
In this example the referer (-e or --referer in curl) is 'localhost'.
Set Header -H "Content-Type: application/json" using GET Request
Example -
curl -H "Content-Type: application/json" -X GET https://jsonplaceholder.typicode.com/posts/1
If u want to Add multiple header
curl -H "Connection: keep-alive" -H "Content-Type: application/json -X GET https://jsonplaceholder.typicode.com/posts/1
精彩评论