我正在尝试连接到FreshBooks API
使用 python 和httplib
模块。我已经设法用这个Requests
包完成了这项工作,但因为我是一个初学者,并且想学习,我也想使用标准 Python 库让它工作。
这就是使用 httplib 的代码:
import base64, httplib
# test script created to connect with my test Freshbooks account
headers = {}
body = '/api/2.1/xml-in'
headers["Authorization"] = "Basic {0}".format(
base64.b64encode("{0}:{1}".format('I have put here my Auth Token', 'user')))
headers["Content-type"] = "application/xml"
# the XML we ll send to Freshbooks
XML = """<?xml version="1.0" encoding="utf-8"?>
<request method="task.list">
<page>1</page>
<per_page>15</per_page>
</request>"""
# Enable the job
conn = httplib.HTTPSConnection('devjam-billing.freshbooks.com')
conn.request('POST', body, None, headers)
resp = conn.getresponse()
print resp.status
conn.send(XML)
print resp.read()
conn.close()
这就是 Freshbooks 的回报:
200
<?xml version="1.0" encoding="utf-8"?>
<response xmlns="http://www.freshbooks.com/api/" status="fail">
<error>Your XML is not formatted correctly.</error>
<code>40010</code>
</response
在我使用 Packages 的第二个脚本中,我得到了相同的响应,我修复了在post()
函数中添加标题:
import requests
XML = """<?xml version="1.0" encoding="utf-8"?>
<request method="task.list">
<page>1</page>
<per_page>15</per_page>
</request>"""
headers = {'Content-Type': 'application/xml'} # set what your server accepts
r = requests.post('https://devjam-billing.freshbooks.com/api/2.1/xml-in', auth= ('my auth token', 'user'), data=XML, headers=headers)
print r.status_code
print r.headers['content-type']
# get the response
print r.text
我尝试通过添加第一个来做类似的事情:
headers["Content-type"] = "application/xml"
没有成功。
有任何想法吗?b64encode 也是一种安全的编码安全选项,还是有更安全的方法?谢谢。