开发者

How do I modify my simple Python code, to take into account HTTP headers?

开发者 https://www.devze.com 2023-02-01 00:59 出处:网络
def URLRequest(url, params, method=\"POST\"): r= urllib2.urlopen(url, data=urllib.urlencode(params)) return r
def URLRequest(url, params, method="POST"):
    r  = urllib2.urlopen(url, data=urllib.urlencode(params))
    return r

In this method, I send a POST request to a certain URL. What if 开发者_开发问答I want to do headers as well? I want to send a dictionary of additional headers (in addition to standard headers).


def URLPost(url, params, method="POST", headers = {}):
    req = urllib2.Request(url)
    for k, v in headers.items():
        req.add_header(k, v)
    r  = urllib2.urlopen(req, data=urllib.urlencode(params))
    return r


With urllib2, you can easily use custom "Handlers" to send additional headers etc. Or see http.client.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号