在Python中使用cURL的帮助
我需要向一个服务器发送一个POST请求。在这个网站的API文档中,有一个使用PHP的cURL的例子:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://api.website.com');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "request=$wrapper");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
;
$data = curl_exec($ch);
curl_close($ch);
但是我的应用是用Python写的,所以我尝试写了类似的代码,但这段代码不管用:
req = urllib2.Request(url, formatted)
response = urllib2.urlopen(req)
html = response.read()
print html+"\n\n"
你能帮我把这个PHP的cURL程序转换成Python的可用代码吗?
谢谢!!
4 个回答
2
curl也可以在Python中使用:http://pycurl.sourceforge.net/
这个例子可以用Python和pycurl这样写:
import pycurl
c = pycurl.Curl()
c.setopt(pycurl.URL, "http://api.website.com")
c.setopt(pycurl.POST, 1)
c.setopt(pycurl.POSTFIELDS, "request=%s" % wrapper)
import StringIO
b = StringIO.StringIO()
c.setopt(pycurl.WRITEFUNCTION, b.write)
c.perform()
c.close()
data = b.getvalue()
你用urllib2写的Python代码看起来没问题,应该可以正常工作。可能在你没有提到的其他地方有错误;能不能请你说得更具体一点?
2
可以考虑使用一个数据包嗅探器来检查cURL是否发送了用户代理信息。如果发送了,而且服务需要这些信息,那么就可以在你的请求中使用add_header()方法(可以在urllib2文档的页面底部找到):
import urllib2
req = urllib2.Request('http://api.website.com/')
# Your parameter encoding here
req.add_header('User-agent', 'Mozilla/5.0')
r = urllib2.urlopen(req)
# Process the response
1
这真有点尴尬,不过...我代码的问题就是用到了urllib和urllib2,但它做的是GET请求,而不是我想要的POST请求!!!
这是我用Wireshark扫描的结果:
1- 使用urllib和urllib2
Hypertext Transfer Protocol
GET / HTTP/1.1\r\n
[Expert Info (Chat/Sequence): GET / HTTP/1.1\r\n]
[Message: GET / HTTP/1.1\r\n]
[Severity level: Chat]
[Group: Sequence]
Request Method: GET
Request URI: /
Request Version: HTTP/1.1
Accept-Encoding: identity\r\n
Host: api.apptrackr.org\r\n
Connection: close\r\n
User-Agent: Python-urllib/2.6\r\n
\r\n
2- 使用PyCurl
Hypertext Transfer Protocol
POST / HTTP/1.1\r\n
[Expert Info (Chat/Sequence): POST / HTTP/1.1\r\n]
[Message: POST / HTTP/1.1\r\n]
[Severity level: Chat]
[Group: Sequence]
Request Method: POST
Request URI: /
Request Version: HTTP/1.1
User-Agent: PycURL/7.19.5\r\n
Host: api.website.com\r\n
Accept: */*\r\n
Content-Length: 365\r\n
[Content length: 365]
Content-Type: application/x-www-form-urlencoded\r\n
\r\n
Line-based text data: application/x-www-form-urlencoded
[truncated] request=%7B%22enc_key%22%3A%22o37vOsNetKgprRE0VsBYefYViP4%2ByB3pjxfkfCYtpgiQ%2ByxONgkhhsxtqAwaXwCrrgx%2BPDuDtMRZNI1ez//4Zw%3D%3D%22%2C%22format%22%3A%22RSA_RC4_Sealed%22%2C%22profile%22%3A%22Ldn%22%2C%22request%22%3A%22bQ%2BHm/
所以代码是能运行的,但对我来说不太对,因为我需要的是POST请求,不过我更倾向于不使用PyCurl。有什么建议吗?
非常感谢!!