协慌网

登录 贡献 社区

如何通过 curl 调用使用 HTTP 请求发送标头?

我希望在 Linux 机器上向我的 Apache 服务器发送一个标头。如何通过卷曲调用实现此目的?

答案

man curl

-H/--header <header>
          (HTTP)  Extra header to use when getting a web page. You may specify
          any number of extra headers. Note that if you should  add  a  custom
          header that has the same name as one of the internal ones curl would
          use, your externally set header will be used instead of the internal
          one.  This  allows  you  to make even trickier stuff than curl would
          normally do. You should not replace internally set  headers  without
          knowing  perfectly well what you're doing. Remove an internal header
          by giving a replacement without content on the  right  side  of  the
          colon, as in: -H "Host:".

          curl  will  make sure that each header you add/replace get sent with
          the proper end of line marker, you should thus not  add  that  as  a
          part  of the header content: do not add newlines or carriage returns
          they will only mess things up for you.

          See also the -A/--user-agent and -e/--referer options.

          This option can be used multiple times to add/replace/remove  multi-
          ple headers.

例:

curl --header "X-MyHeader: 123" www.google.com

您可以通过添加-v选项查看 curl 发送的请求。

得到:

使用 JSON:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" http://hostname/resource

使用 XML:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource

POST:

用于发布数据:

curl --data "param1=value1&param2=value2" http://hostname/resource

对于文件上传:

curl --form "[email protected]" http://hostname/resource

RESTful HTTP 帖子:

curl -X POST -d @filename http://hostname/resource

用于登录站点(auth):

curl -d "username=admin&password=admin&submit=Login" --dump-header headers http://localhost/Login
curl -L -b headers http://localhost/

PHP 中

curl_setopt($ch, CURLOPT_HTTPHEADER, array('HeaderName:HeaderValue'));

或者您可以设置多个:

curl_setopt($ch, CURLOPT_HTTPHEADER, array('HeaderName:HeaderValue', 'HeaderName2:HeaderValue2'));