简体   繁体   中英

python urllib2 post data

I need to pass some data to the following urllib2 request,

    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)

will

connection = opener.open(request, data)

work? if not how can I pass data to the request?

UPDATE:

I think i can pass it this way

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

You can use the method urllib2.Request.add_data:

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

This converts it to a POST request.

import urllib2
import json

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

But i recommend to you use requests is the best option to handle http calls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM