开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜