如何在Python中发送HTTP Get Web Request?

How do you send an HTTP Get Web Request in Python?

本问题已经有最佳答案,请猛点这里访问。

我无法将数据发送到网站,也无法在python中获得响应。我也看到过类似的问题,但似乎没有一个能达到我的目标。

这是我试图移植到python的C代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    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);
            }
        }
     }

下面是我在python中的尝试:

1
2
3
4
5
6
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

任何帮助都将不胜感激!


你可以用urllib2

1
2
3
import urllib2
content = urllib2.urlopen(some_url).read()
print content

也可以使用httplib

1
2
3
4
5
6
7
import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("HEAD","/index.html")
res = conn.getresponse()
print res.status, res.reason
# Result:
200 OK

或者请求库

1
2
3
4
5
import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code
# Result:
200


在python中,您可以使用urllib2(http://docs.python.org/2/library/urllib2.html)来完成所有这些工作。

简单地说:

1
2
3
import urllib2
f =  urllib2.urlopen(url)
print f.read()

将打印收到的HTTP响应。

要传递get/post参数,可以使用urllib.urlencode()函数。有关详细信息,请参阅正式的URLLIB2教程。