【问题标题】:Convert curl get command to urllib get request将 curl get 命令转换为 urllib get 请求
【发布时间】:2018-07-24 22:08:10
【问题描述】:

我有一个 curl 请求,我想在 python2 中转换为 urllib。

curl 有效并给儿子响应:

curl -i -X GET -H "X-AUTH-TOKEN: $AUTH_TOKEN" \
-H "Accept: application/json" \
"https://api.xyz.com/apiv1.2/reports/nodes?start_date=2014-04-01&end_date=2014-04-21"

我尝试了以下代码,它不断将我重定向到登录 html 页面作为响应。如何将上面的 curl 请求转换为 urllib?

    headers = {"Content-Type": "application/json", "AUTH_TOKEN":'1234yyzxx'}
    data = urllib.urlencode(values)
    request = urllib2.Request(ENDPOINT + '?' + data, headers=headers)
    response = urllib2.urlopen(request)
    text = response.read()
    print text

【问题讨论】:

    标签: python-2.7 curl httprequest urllib2


    【解决方案1】:

    使用请求库找到它。

    import requests
    import json
    
    response = requests.get(ENDPOINT, headers=headers, params=values)
    text = json.loads(response.text)
    

    但是,我不介意所有非弃用库(urllib、urllib2、urllib3 等)中的答案。

    哪个更快?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-18
      • 2021-03-29
      • 2019-11-04
      • 1970-01-01
      • 2021-02-10
      • 1970-01-01
      • 2016-05-20
      相关资源
      最近更新 更多