In Python 2, the equivalent of urllib.request.Request
is urllib2.Request
.
Here’s an example:
import urllib2
url = "https://example.com"
headers = {"User-Agent": "My User Agent"}
data = "foo=bar&baz=qux"
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)
print(response.read())
This code creates a Request
object with the specified URL, data, and headers, and then uses urlopen
to send the request and get the response.
Note that in Python 2, urllib2
is used instead of urllib.request
, and the Request
class is used to create a request object.
In Python 3.x, urllib.request.Request
is used to create a request object, and it’s much simpler to use. For example:
import urllib.request
url = "https://example.com"
headers = {"User-Agent": "My User Agent"}
data = "foo=bar&baz=qux"
req = urllib.request.Request(url, data.encode("utf-8"), headers)
response = urllib.request.urlopen(req)
print(response.read().decode("utf-8"))
This code creates a Request
object with the specified URL, data, and headers, and then uses urlopen
to send the request and get the response.