【问题标题】:How can curl perform a get request with a data payload?curl 如何使用数据有效负载执行获取请求?
【发布时间】:2020-02-17 00:22:02
【问题描述】:

ElasticSearch 上的介绍材料包括以下示例curl 请求:

curl -X GET "localhost:9200/_search?pretty" -H 'Content-Type: application/json' -d'
{
    "query": {
        "query_string" : {
            "query" : "(new york city) OR (big apple)",
            "default_field" : "content"
        }
    }
}
'

这个请求有两个我认为不兼容的参数:

  • -X GET,指定请求为GET
  • -d [...],指定请求有数据负载。

我认为只能在 PUTPOST 请求中指定数据负载,因为 GET 请求没有任何数据负载的概念。这是一个有效的curl 命令吗?它到底有什么作用?

【问题讨论】:

    标签: elasticsearch curl get


    【解决方案1】:

    curl以上的请求是一个有效的请求,实际上如果你有索引和数据,那么你可以检查你的命令的输出。

    我在我的系统和 ES 索引中尝试了它,它给了我正确的响应。

    curl -v -X GET "localhost:9500/querytime/_search?pretty" -H 'Content-Type: application/json' -d'
    {
        "query": {
            "query_string" : {
                "query" : "(avengers) OR (big apple)",
                "default_field" : "movie_name"
            }
        }
    }'
    *   Trying ::1...
    * TCP_NODELAY set
    * Connected to localhost (::1) port 9500 (#0)
    > GET /querytime/_search?pretty HTTP/1.1
    > Host: localhost:9500
    > User-Agent: curl/7.64.1
    > Accept: */*
    > Content-Type: application/json
    > Content-Length: 156
    >
    * upload completely sent off: 156 out of 156 bytes
    < HTTP/1.1 200 OK
    < content-type: application/json; charset=UTF-8
    < content-length: 905
    <
    {
      "took" : 4,
      "timed_out" : false,
      "_shards" : {
        "total" : 1,
        "successful" : 1,
        "skipped" : 0,
        "failed" : 0
      },
      "hits" : {
        "total" : {
          "value" : 3,
          "relation" : "eq"
        },
        "max_score" : 0.14874382,
        "hits" : [
          {
            "_index" : "querytime",
            "_type" : "_doc",
            "_id" : "1",
            "_score" : 0.14874382,
            "_source" : {
              "movie_name" : "Avengers: Infinity War"
            }
          }
        ]
      }
    }
    

    在 curl 命令的官方手册中提到,如果您使用的是基于*nix 的系统,那么您可以在下面的curl 手册中搜索。

    -G, --get 使用时,此选项将使所有使用 -d、--data、--data-binary 或 --data-urlencode 指定的数据用于 HTTP GET 请求而不是 POST 请求,否则将是 用过的。这 数据将附加到带有“?”的 URL分隔符

    正如this SO 回答中所解释的,它还依赖于网络服务器来解析 GET 请求中的正文。

    【讨论】:

    • 我明白了,所以 GET 请求有一个空的主体是服务器解释的建议,而不是 HTTP 协议的硬性要求,服务器可以选择接受带有主体的 GET 请求。我仍然认为这不是协议所定义的意图,但我明白为什么它很方便。
    • @AlekseyBilogur,我同意你的观点,但是这取决于实现者,尤其是在 ES 中,你会看到很多这样的请求:-)。顺便说一句,感谢您的支持和接受,它激励我们超越自我来帮助社区
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    • 2017-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多