我必须向服务器发送请求。在该网站的 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 的有效转换吗?
谢谢你!!
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 代码看起来没问题,应该可以工作。可能您没有提到的其他内容有错误;您能说得更具体一些吗?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)