• 请不要在回答技术问题时复制粘贴 AI 生成的内容
ethsol
V2EX  ›  程序员

作为一个 python 新手,我很无语, urllib2 的 add_header 搞了一天,求助解决方法

  •  1
     
  •   ethsol · Oct 12, 2016 · 8952 views
    This topic created in 3687 days ago, the information mentioned may be changed or developed.

    代码

    ...
    >>> h = {"Content-Type": "application/json"}
    >>> req = urllib2.Request(url,js,h)
    >>> req.has_header("Content-Type")
    False
    >>> req.get_header("Content-type")
    'application/json'
    

    key 被 capitalize 了,我这个 header 就要 Content-Type 的,怎么搞?

    18 replies  •  2016-10-13 13:02:08 +08:00
    upczww
    upczww
    Oct 12, 2016 via Smartisan T1❤️2
    1
    你应该试试 requests.
    HTTP for Humans.
    shadowmydx
    shadowmydx
    Oct 12, 2016❤️2
    2
    这个很简单,这个 header 是 Request 对象中一个叫 headers 的成员,如果一定要大写,你直接这么写就可以:
    h = {"Content-Type": "application/json"}
    req = urllib2.Request(url, js, headers=h)
    req.headers = h
    print req.has_header("Content-Type")
    print req.get_header("Content-Type")
    ethsol
    ethsol
    OP
    Oct 12, 2016
    3
    @shadowmydx 可以了,但是为什么要额外加 req.headers = h
    ethsol
    ethsol
    OP
    Oct 12, 2016
    4
    @upczww 很好 requests 更简洁
    ThinkCat
    ThinkCat
    Oct 12, 2016
    5
    你应该用下 requests , 这个真心好用
    ryd994
    ryd994
    Oct 12, 2016 via Android
    6
    因为 HTTP 协议本来就规定 header 不分大小写: https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
    ubear1991
    ubear1991
    Oct 12, 2016
    7
    用 requests
    TKKONE
    TKKONE
    PRO
    Oct 12, 2016
    8
    看到那么多人推荐 requests ,我就放心了。
    还是用 requests 吧,妥妥的
    ethsol
    ethsol
    OP
    Oct 12, 2016
    9
    已用 requests ,妥妥的
    jixiangqd
    jixiangqd
    Oct 12, 2016
    10
    试过 requests 并发性能不是很好。。。不知道为什么
    qweweretrt515
    qweweretrt515
    Oct 12, 2016
    11
    requests 啊
    sherwinkoo
    sherwinkoo
    Oct 12, 2016
    12
    @jixiangqd 你怎么测试的?
    jixiangqd
    jixiangqd
    Oct 12, 2016
    13
    @sherwinkoo 试过自带进程池、线程池模块、 gevent 协程:都是 urllib2 性能最好,差的还不是一点半点。不知道是不是有什么配置可以改进并发性能,没有深入研究
    purrgil
    purrgil
    Oct 13, 2016
    14
    life is short,you neet requests
    purrgil
    purrgil
    Oct 13, 2016
    15
    Life is short,you need requests.
    ibigbug
    ibigbug
    Oct 13, 2016
    16
    rfc 是规定 http header 不区分大小写的,你可能无语错地方了
    shadowmydx
    shadowmydx
    Oct 13, 2016
    17
    @zong400 因为 urlib2 在构建 Request 对象时对你传入的参数进行了统一的处理,其中,处理 header 后,将其赋予一个成员变量 headers 。因此,你只需要重新替换掉这个成员就可以了。
    chy373180
    chy373180
    Oct 13, 2016
    18
    requests 何来的并发性能不是很好。。。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2389 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 49ms · UTC 13:02 · PVG 21:02 · LAX 05:02 · JFK 08:02
    ♥ Do have faith in what you're doing.