ChatGPT解决这个技术问题 Extra ChatGPT

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

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

有一个很好的方法可以通过示例学习如何使用 curl 处理 http 请求。下载最新版本的 Postman,在用户界面级别根据需要进行任何 http 请求配置(例如,使用 headers 和 json body),然后单击“生成代码”并选择“curl”选项.它为您提供了等效的命令行。
这是上述方法 youtu.be/L3m6cpQPsV0 的 2 分钟视频链接

T
Tader

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.

示例 1:单个标题

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

示例 2:多个标题

curl --header "Accept: text/javascript" --header "X-Test: hello" -v www.google.com

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


如果要发送多个标头使用多个 --header,没关系,curl 会将每个标头解析为不同的标头。无法在相同的 --header 参数中分隔标头。例如: curl --header "Accept: javascript" --header "test: hello" -v www.google.com
如果人们想要示例,我将把它留在这里:bropages.org
手册页(至少在 OSX 上)现在包含一个示例:示例:# curl -H "X-First-Name: Joe" 192.168.0.1
@MartinKonicek 和其他人:我强烈推荐 tldr utiltiy(brew 等安装 tldr)。它的唯一例子。例如“- 使用自定义 HTTP 方法发送带有额外标头的请求:curl -H 'X-My-Header: 123' -X PUT example.com
这篇文章应该是公认的答案。当前接受的答案,无论多么正确,都只能隐含地回答 OPs 问题。
R
Randhi Rupesh

得到:

使用 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

邮政:

对于发布数据:

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

对于文件上传:

curl --form "fileupload=@filename.txt" 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/

RESTful 帖子的@filename 是什么意思?您是否将文件发布到 REST 服务器?这对我来说似乎很奇怪
对于稍后到达的人可能想知道同样的事情......@ 表示法是一种读取数据以从文件发送到服务器的方式,而不是将其内联到 curl 请求中。您本身并不发布文件,而是将文件的内容作为 POST 请求的主体发布。
更详细的答案在这里:stackoverflow.com/questions/14978411/… :)
如果我正确理解标头的用法:标头 Accept 用于希望拥有此功能的 客户端(询问/请求),但标头 Content-Type 只是服务器 回答仅此而已,并没有误会客户的愿望:“我想要这种类型的内容”。正确的?所以对于 GET curl -i -H "Accept: application/json" http://hostname/resource 应该是它。我错了吗?请参阅 developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type «在响应中,Content-Type 标头告诉客户端返回内容的实际内容类型。»
@andreas.naturwiki,再次不要混淆。在 MDN 中,«In response...» 表示响应中的 Content-Type。不是请求。 Content-Type 总是指两方之间传输的数据类型。如果它在请求标头上,则意味着客户端说“是的,我正在向您发送数据类型 application/json”到服务器。如果它正在响应,则意味着服务器向客户端说“现在我正在向您发送数据类型 text/plain”。
s
simhumileco

在 PHP 中:

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

或者您可以设置多个:

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

@James 在某些情况下它可以正常工作,但在其他情况下,CURL 会发送一个额外的标题“期望:100-继续” - 关于如何删除它的任何想法?
@coding_idiot:您可以在标头值数组中传递“期望:”以禁用它。例如: curl_setopt($ch,CURLOPT_HTTPHEADER,array('HeaderName: HeaderValue', 'Expect:'));
OP 没有说任何关于 PHP 的想法
标头名称用下划线大写,并以 HTTP_ 为前缀。例如,“保护令牌”变为“HTTP_PROTECTION_TOKEN”。
@hanshenrik 是的,但是 OP 也没有说任何关于命令行的事情。事实上,这个问题应该因为不清楚而被搁置。今天一个新手不会逃脱这样一个草率的问题。
C
Community

使用 -H or --header

手册页:http://curl.haxx.se/docs/manpage.html#-H


-H 选项可以在命令提示符下使用,例如: curl -H "pwd:123" localhost/test.php
谢谢。简短,简洁,并由文档链接覆盖。但是链接已经过时了,现在的新链接是 curl.haxx.se/docs/manpage.html#-H
V
Vietnhi Phuvan

GET(多个参数):

curl -X  GET "http://localhost:3000/action?result1=gh&result2=ghk"

或者

curl --request  GET "http://localhost:3000/action?result1=gh&result2=ghk"

或者

curl  "http://localhost:3000/action?result1=gh&result2=ghk"

或者

curl -i -H "Application/json" -H "Content-type: application/json"  "http://localhost:3000/action?result1=gh&result2=ghk"

谢谢。我没有意识到这种网址的强制性引号。
R
Rajendra Prasad Patil

我使用邮递员。

执行您想做的任何呼叫。然后,postman 提供了一个方便的工具来显示 curl 代码。

https://i.stack.imgur.com/ByU2a.png

https://i.stack.imgur.com/7jlsh.png


这是加快速度的好方法,但如果您在 Windows 上使用 shell 脚本,请注意转义单引号或双引号,因为 shell 脚本有它自己的格式要求
虽然 postman 是一个不错的工具,但是当你没有像 Kubernetes pod 那样的图形环境时,它就没用了。学习 curl,你总是可以测试休息。
M
Manuel Pirez

您还可以发送多个标头、数据(例如 JSON),并将调用方法(POST、GET)指定到单个 CUrl 调用中,如下所示:

curl -X POST(Get or whatever) \
  http://your_url.com/api/endpoint \
  -H 'Content-Type: application/json' \
  -H 'header-element1: header-data1' \
  -H 'header-element2: header-data2' \

......更多标题......

  -d '{
  "JsonExArray": [
    {
      "json_prop": "1",
    },
    {
      "json_prop": "2",
    }
  ]
}'

我认为它在 bash 中使用,而不是在 cmd 中。我对吗 ?让我知道先生。
是的,那是它的狂欢。
G
Graham Perks

我已经从 curl 切换到 Httpie;语法如下:

http http://myurl HeaderName:value

s
simhumileco

如果您想发送自定义标头,您可以这样做:

curl -v -H @{'custom_header'='custom_header_value'} http://localhost:3000/action?result1=gh&result2=ghk

这不是试图从名为 {'custom_header'='custom_header_value'} 的文件中读取标题吗?
D
DINA TAKLIT

在通过 windows 的 anaconda 环境中,命令应该是:GET,例如:

curl.exe http://127.0.0.1:5000/books 

发布或修补数据,例如:

curl.exe http://127.0.0.1:5000/books/8 -X PATCH -H "Content-Type: application/json" -d '{\"rating\":\"2\"}' 

PS:为json数据添加反斜杠以避免此类错误=> Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)

并使用 curl.exe 而不是 curl 只是为了避免此问题:

Invoke-WebRequest : Cannot bind parameter 'Headers'. Cannot convert the "Content-Type: application/json" value of type
"System.String" to type "System.Collections.IDictionary".
At line:1 char:48
+ ... 0.1:5000/books/8 -X PATCH -H "Content-Type: application/json" -d '{\" ...
+                                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Invoke-WebRequest], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

这与最初发布的问题几乎无关。
@MarkHu 它响应问题标题,而不是问题正文:)。有许多类似于问题标题的问题,所以他们会采纳我的答案,而我就是其中之一,所以一旦我找到答案,我就会分享它。
S
Sanjay Bharwani

以下是最常见的 http 方法的一些 curl 命令。

这里考虑的域对象是

@Data
@NoArgsConstructor
@AllArgsConstructor
@Document
@Validated
public class Movie {
    @Id
    private String id;
    private String name;
    @NotNull
    private Integer year;
    @NotNull
    private List<String> cast;
    private LocalDate release_date;
}

后期制作电影

curl -i \
-d '{"id":1, "name": "Dhoom", "year":2004,"cast":["John Abraham", "Abhishek Bachan"],"release_date": "2004-06-15"}' \
-H "Content-Type: application/json" \
-X POST http://localhost:8080/v1/movies

获取所有电影

curl -i http://localhost:8080/v1/movies

按 ID 获取电影

curl -i http://localhost:8080/v1/movies/1

放更新电影

curl -i \
-d '{"id":1, "name": "Dhoom", "year":2005,"cast":["John Abhraham", "Abhishek Bachhan", "Uday Chopra", "Isha Deol"],"release_date": "2005-03-25"}' \
-H "Content-Type: application/json" \
-X PUT http://localhost:8080/v1/movies/1

删除电影

curl -i -X DELETE http://localhost:8080/v1/movies/1