- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我需要将字符串(无字典)中的数据作为调用 REST API 的主体。
当我打电话时
r = requests.put(url, data = string)
然后我可以在调用之后在 r.request.body
中看到它是 None
。此外,服务器响应“411 需要长度”错误。
但是,当我尝试使用字典而不是字符串时,它会起作用,因为服务器会使用正确的 JSON 数据进行响应。此外,在那种情况下,我可以在 r.request.body
中看到正确的数据。
有什么想法吗?
PS:我使用的是 Python 2.7.3 和 Python-requests 1.2.0
最佳答案
即使在三次尝试澄清问题之后,仍然不清楚你在这里问的是什么,但我可以尝试抛出足够的信息让你找出答案。
首先,r = requests.put(url, data = string)
返回一个Response
,它没有body
,但它确实有一个request
,和一个history
0个或多个重定向请求,所有这些都是PreparedRequest
对象,它们确实有body
属性。
另一方面,如果您执行 r.requests.Request(method='PUT', url=url, data=string)
,那将返回一个 Request
,它必须是 prepare()
d 才能有主体。
无论哪种方式,如果我做一个简单的测试并查看结果,我发现 body
总是正确的:
>>> resp = requests.put('http://localhost/nosuchurl', data='abc')
>>> resp.request.body
'abc'
>>> resp = requests.put('http://localhost/redirect_to_https', data='abc')
>>> resp.history[-1].request.body
'abc'
>>> req = requests.Request(method='PUT', url='http://localhost/nosuchurl', data='abc')
>>> preq = req.prepare()
>>> preq.body
'abc'
我最好的猜测是你需要查看 resp.history[0].request.body
,但你正在查看 resp.request.body
,或类似的东西。
如果Redirection and History快速入门教程中的内容没有帮助,请阅读详细的 API 文档,或者尝试所有这些文档,直到您弄明白为止。
或者这样做:
resp = request.put('http://localhost/nosuchurl', data='abc', allow_redirects=False)
然后手动进行重定向处理。
关于Python 请求 : How to PUT a string in body?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16204690/
我是一名优秀的程序员,十分优秀!