使用 Python 请求 post 方法但得到 401 响应代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28306077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Python request post method but getting 401 response code
提问by Peter Chao
I am using Python request module post method to process json data, like so.
我正在使用 Python 请求模块 post 方法来处理 json 数据,就像这样。
r = requests.post(url,data=json.dumps(payload),headers=headers)
However I am getting response[401]
. Does it mean I need to first authorize it
by adding login first?
但是我得到response[401]
. 这是否意味着我需要先通过添加登录来授权它?
回答by Dan
A 401
response, as you noticed, means that you need to authenticate in order to make the request. How you do this depends on the auth system in place, but your comment "I use HTTPBasicAuth(user, password) that give me response code of 200" suggests that it's just Basic Auth - which is easy to deal with in requests
.
一个401
回应,因为你注意到了,意味着你需要进行身份验证,以使该请求。您如何执行此操作取决于适当的身份验证系统,但您的评论“我使用 HTTPBasicAuth(user, password) 给我 200 的响应代码”表明它只是基本身份验证 - 在requests
.
Anywhere you do a requests
call, add the kwarg auth=(USERNAME, PASSWORD)
- so for your example above, you'd do r = requests.post(url,data=json.dumps(payload),headers=headers, auth=(USERNAME, PASSWORD))
(replacing USERNAME and PASSWORD with the right values, as shown here.
任何地方,你做一个requests
呼叫,添加kwarg auth=(USERNAME, PASSWORD)
-所以你上面的例子,你会做r = requests.post(url,data=json.dumps(payload),headers=headers, auth=(USERNAME, PASSWORD))
(用正确的值替换用户名和密码,如图所示这里。