Can';在Python中使用httplib无法获得成功的响应
我正在尝试使用python和Can';在Python中使用httplib无法获得成功的响应,python,xml,httplib,Python,Xml,Httplib,我正在尝试使用python和httplib模块连接到FreshBooks API。我已经成功地使用请求包完成了这项工作,但是因为我是初学者,并且想学习,所以我还想使用标准Python库使其工作 这就是使用httplib的代码: import base64, httplib # test script created to connect with my test Freshbooks account headers = {} body = '/api/2.1/xml-in' headers[
httplib
模块连接到FreshBooks API
。我已经成功地使用请求
包完成了这项工作,但是因为我是初学者,并且想学习,所以我还想使用标准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()
在我使用包的第二个脚本中,我得到了相同的响应,我修复了在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
没有成功
有什么想法吗?另外,b64encode是一个安全的编码选项,还是有更安全的方法?谢谢。您似乎在错误的时间发送数据。从(我的)重点看 HTTPConnection.send(数据) 将数据发送到服务器。只有在调用了endheaders()方法之后和调用了getresponse()之前,才可以直接使用它 就你而言:
conn.endheaders()
conn.send(XML)
resp = conn.getresponse()
您似乎在错误的时间发送数据。从(我的)重点看 HTTPConnection.send(数据) 将数据发送到服务器。只有在调用了endheaders()方法之后和调用了getresponse()之前,才可以直接使用它 就你而言:
conn.endheaders()
conn.send(XML)
resp = conn.getresponse()
实际上,您需要在请求中发送POST数据(XML字符串),因此,替换为:
conn.request('POST', body, None, headers)
resp = conn.getresponse()
print resp.status
conn.send(XML)
print resp.read()
为此:
conn.request('POST', body, XML, headers)
resp = conn.getresponse()
print resp.status
print resp.read()
我希望有帮助 您实际上需要在请求中发送POST数据(XML字符串),因此,请替换以下内容:
conn.request('POST', body, None, headers)
resp = conn.getresponse()
print resp.status
conn.send(XML)
print resp.read()
为此:
conn.request('POST', body, XML, headers)
resp = conn.getresponse()
print resp.status
print resp.read()
我希望有帮助