如何在Python中发送HTTP Get Web Request? [英] How do you send an HTTP Get Web Request in Python?
本文介绍了如何在Python中发送HTTP Get Web Request?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法将数据发送到网站并在Python中获得响应。我已经看到了类似的问题,但它们似乎都没有实现我的目标。
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.
这是我想要移植到Python的C#代码:
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);
}
}
}
这是我在Python中的尝试:
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!
推荐答案
您可以使用 urllib2
import urllib2
content = urllib2.urlopen(some_url).read()
print content
您也可以使用 httplib
import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("HEAD","/index.html")
res = conn.getresponse()
print res.status, res.reason
# Result:
200 OK
或请求库
import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code
# Result:
200
这篇关于如何在Python中发送HTTP Get Web Request?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文