【问题标题】:Follow links in cURL responses using a loop使用循环跟踪 cURL 响应中的链接
【发布时间】:2020-11-15 08:31:14
【问题描述】:
curl -H "Accept: application/json" 'http://example.com'

我得到的回应是

{"next":"/gibberish"}

所以我执行另一个请求:

curl -H "Accept: application/json" 'http://example.com/gibberish'

我得到的回应是

{"next":"/anotherGibberish"}

我希望能够执行 curl 请求,获取 next 信息并循环进入下一个请求。

你们知道如何在 bash 中执行此操作吗?

编辑: 任何使用 jq 的帮助也会很棒。 最后一个响应是一个身份验证失败的 JSON 响应 - 我应该停止循环。

{"unauthorized":"Authenticate with username and password"}

【问题讨论】:

  • @oguzismail 当没有{"next":"/anotherGibberish"}response 时
  • 是的。最后的响应是认证失败{"unauthorized":"Authenticate with username and password"}

标签: bash macos shell curl jq


【解决方案1】:

假设next 键在响应中不存在,或者它的值是一个字符串,当附加到http://example.com 时形成一个有效的 URL:

#!/bin/bash -
next=/
while resp=$(curl -sS "http://example.com$next"); do
  if ! next=$(jq -er '.next' <<< "$resp"); then
    # `resp' is the final response here
    # , do whatever you want with it
    break
  fi
done

【讨论】:

  • 只需一次修改就可以很好地工作。在 curl 请求中,我添加了标题 -H "Accept: application/json" - 非常感谢!
猜你喜欢
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-07
  • 2015-03-24
  • 1970-01-01
相关资源
最近更新 更多