python urllib2发布数据

时间:2014-08-05 17:31:34

标签: python linux urllib2 urllib

我需要将一些数据传递给以下urllib2请求,

    handler = urllib2.HTTPSHandler()
    opener = urllib2.build_opener(handler)
    request = urllib2.Request(url)
    request.add_header("Accept",'application/*+xml;version=5.5')
    request.add_header("x-vcloud-authorization",authtoken)
    request.get_method = lambda: method
    data = "some XML request"
    try:
        connection = opener.open(request)
    except urllib2.HTTPError,e:
        connection = e

    if connection.code == 200:
        data = connection.read()
        #print "Data from Entity"
        #print "Data :", data
    else:
        print "ERROR", connection.code
        sys.exit(1)

connection = opener.open(request, data)

工作?如果不是,我如何将数据传递给请求?

更新

我想我可以通过这种方式传递

request = urllib2.Request(url, data="some data")

2 个答案:

答案 0 :(得分:2)

您可以使用方法urllib2.Request.add_data:

request.add_header('xxxx', 'vvvv')
request.add_data('some XML request')
opener.open(request)

将其转换为POST请求。

答案 1 :(得分:1)

import urllib2
import json

# Whatever structure you need to send goes here:
jdata = json.dumps({"username":"...", "password":"..."})
urllib2.urlopen("http://www.example.com/", jdata)

但我建议您使用requests是处理http调用的最佳选择。