代码之家  ›  专栏  ›  技术社区  ›  Amber Sonlit

无法使用Python请求库从Web服务器获取时间(状态代码401)

  •  0
  • Amber Sonlit  · 技术社区  · 8 月前

    我目前正在开发一个Python脚本,该脚本可以不断地从web服务器获取当前时间并打印出来。然而,我遇到了身份验证问题,导致状态代码为401。我已经提供了所有必要的标头和访问令牌,但响应表明存在身份验证问题。web服务器的链接: http://cyber.cs.du.edu/timekeeper/ (这是我所在大学为完成本次任务而制作的一个假设网站)

    from datetime import datetime
    import time
    
    def get_current_time():
        try:
            time_api_url = "http://cyber.cs.du.edu/timekeeper/api/v1/time"
            headers = {
                'Accept': 'application/json, text/javascript, */*; q=0.01',
                'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpcCI6IjE3Mi4xNy4wLjEiLCJybmQiOiIxMWEzN2Q1YTQ3ZTQxY2ViNzMwZWEyNDg5N2MzOWMwZTUwM2QzNDU1NGQ5MjFjNmE0NGY2NGJlMDI5OTkxYTU5IiwiYWdlbnQiOiJNb3ppbGxhLzUuMCAoTWFjaW50b3NoOyBJbnRlbCBNYWMgT1MgWCAxMF8xNV83KSBBcHBsZVdlYktpdC81MzcuMzYgKEtIVE1MLCBsaWtlIEdlY2tvKSBDaHJvbWUvMTE5LjAuMC4wIFNhZmFyaS81MzcuMzYiLCJleHAiOjE2OTk1NTM4NTJ9.fFIpbEmAhotro4MgL0GTSbYrtl--t92MTFKnNX-tnfw',
                'Connection': 'keep-alive',
                'Cookie': '_cap=344691521684862355; _fbp=fb.1.1684862355417.17791420; _attrb=%22293b6266-57cb-4269-93ef-a6308b74f593%22; _scid=8509b8d8-90ea-4e40-840d-6f19637fbe27; _ga_S2V8B3QG10=GS1.2.1693412411.17.0.1693412411.0.0.0; _gcl_au=1.1.1900453194.1694548891; _ga_EQYTG2FRZB=GS1.1.1694643835.4.1.1694643921.0.0.0; _ga_3R9779E9CE=GS1.1.1697141496.2.1.1697141511.0.0.0; _ga_YD6NSK449L=GS1.1.1698702601.3.0.1698702602.59.0.0; _ga_G3QL5ZJ7V2=GS1.1.1698706614.2.1.1698706721.60.0.0; cebs=1; _gid=GA1.2.7375447.1699384534; _ga_KDCJP7WQR2=GS1.2.1699384534.32.1.1699384541.0.0.0; _sctr=1%7C1699340400000; cebsp_=3; _scid_r=8509b8d8-90ea-4e40-840d-6f19637fbe27; _ce.s=v~cdafb05ef8918fcf3bc3bb022cd2ae51233ea0de~lcw~1699393884317~vpv~3~v11.cs~348336~v11.s~690beb20-7db7-11ee-8ffb-e3470a664e62~v11.sla~1699393884364~gtrk.la~loov8lm7~v11.send~1699393884316~lcw~1699393884366; _ga_7KPJG812Y3=GS1.1.1699394129.1.1.1699394621.0.0.0; _ga=GA1.2.1823087093.1684861047; _ga_CMGRJVENZ2=GS1.1.1699484166.33.0.1699484166.60.0.0; _ga_0F4BY0DEFX=GS1.1.1699484166.5.0.1699484166.0.0.0; _ga_RPN0H7RH0P=GS1.2.1699484369.203.1.1699484382.0.0.0; bt=1699553552.3100853; _acdk=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0cyI6MTY5OTU1MzU1MiwiZXhwIjoxNjk5NTUzNTYyLCJ0b2tlbiI6ImV5SmhiR2NpT2lKSVV6STFOaUlzSW5SNWNDSTZJa3BYVkNKOS5leUpwY0NJNklqRTNNaTR4Tnk0d0xqRWlMQ0p5Ym1RaU9pSXhNV0V6TjJRMVlUUTNaVFF4WTJWaU56TXdaV0V5TkRnNU4yTXpPV013WlRVd00yUXpORFUxTkdRNU1qRmpObUUwTkdZMk5HSmxNREk1T1RreFlUVTVJaXdpWVdkbGJuUWlPaUpOYjNwcGJHeGhMelV1TUNBb1RXRmphVzUwYjNOb095QkpiblJsYkNCTllXTWdUMU1nV0NBeE1GOHhOVjgzS1NCQmNIQnNaVmRsWWt0cGRDODFNemN1TXpZZ0tFdElWRTFNTENCc2FXdGxJRWRsWTJ0dktTQkRhSEp2YldVdk1URTVMakF1TUM0d0lGTmhabUZ5YVM4MU16Y3VNellpTENKbGVIQWlPakUyT1RrMU5UTTROVEo5LmZGSXBiRW1BaG90cm80TWdMMEdUU2JZcnRsLS10OTJNVEZLbk5YLXRuZncifQ.lkFT0blGLG50DJy_jfQUFuUdHDhnId1WBBk68vIQbeM',
                'Host': 'cyber.cs.du.edu',
                'Referer': 'http://cyber.cs.du.edu/timekeeper/',
                'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36',
                'X-Requested-With': 'XMLHttpRequest',
                'X-Timekeeper-Channel': 'Web'
            }
    
            response = requests.get(time_api_url, headers=headers)
    
            print(response)
    
            if response.status_code == 200:
                try:
                    current_time = response.json().get('current_time')
                    formatted_time = datetime.utcfromtimestamp(current_time).strftime('%Y-%m-%d %H:%M:%S')
                    print(formatted_time)
                except ValueError:
                    print("Invalid JSON response")
    
            else:
                print(f"Error: {response.text}")
    
        except Exception as e:
            print(f"An error occurred: {e}")
    
    if __name__ == "__main__":
        try:
            while True:
                get_current_time()
                time.sleep(1)  # Adjust the sleep interval as needed
        except KeyboardInterrupt:
            print("Script stopped.")
    

    我使用Python请求库向时间API发出GET请求。 我已经包含了必要的标题,我相信访问令牌和cookie是正确的。 然而,我一直收到一个401状态代码,错误为“未授权”

    我已经仔细检查了访问令牌和cookie的正确性,并确保访问令牌具有所需的范围。

    使用正确的访问令牌和Cookie,脚本应该成功地向时间API端点发出请求并打印当前时间。

    尽管提供了正确的访问令牌,但是什么原因导致了401未经授权的错误?还有我可能缺少的其他标题或参数吗?

    1 回复  |  直到 8 月前
        1
  •  0
  •   Andrej Kesely    8 月前

    要从服务器获得正确的结果,可以使用以下示例:

    import re
    
    import requests
    
    url = "http://cyber.cs.du.edu/timekeeper/api/v1/time"
    
    headers = {
        "X-TimeKeeper-Channel": "Web",
    }
    
    with requests.session() as s:
        html_text = s.get("http://cyber.cs.du.edu/timekeeper/").text
    
        token = re.search(r'__window_token = "([^"]+)', html_text).group(1)
        headers["Authorization"] = f"Bearer {token}"
        s.headers.update(headers)
        response = s.get(url).json()
    
        print(response)
    

    打印:

    {'day': 9, 'hour': 21, 'microsecond': 754999, 'minute': 41, 'month': 11, 'second': 8, 'year': 2023}