This question already has an answer here:
I am having trouble sending data to a website and getting a response in Python. I have seen similar questions, but none of them seem to accomplish what I am aiming for.
This is my C# code I'm trying to port to Python:
static void Request(Uri selectedUri)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(selectedUri);
request.ServicePoint.BindIPEndPointDelegate = BindIPEndPointCallback;
request.Method = "GET";
request.Timeout = (int)Timeout.TotalMilliseconds;
request.ReadWriteTimeout = (int)Timeout.TotalMilliseconds;
request.CachePolicy = CachePolicy;
request.UserAgent = UserAgent;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader responseReader = new StreamReader(response.GetResponseStream()))
{
string responseText = responseReader.ReadToEnd();
File.WriteAllText(UrlFileName, responseText.Trim(), Encoding.ASCII);
}
}
}
Here is my attempt in Python:
def request():
web = httplib.HTTPConnection('https://someurl.com');
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
web.request("GET", "/heartbeat.jsp", headers);
response = web.getresponse();
stream = ""; #something is wrong here
Any help would be appreciated!
In Python, you can use
urllib2
(http://docs.python.org/2/library/urllib2.html) to do all of that work for you.Simply enough:
Will print the received HTTP response.
To pass GET/POST parameters the
urllib.urlencode()
function can be used. For more information, you can refer to the Official Urllib2 TutorialYou can use urllib2
Also you can use httplib
or the requests library