【问题标题】:Send x-api-key with POST request header Python使用 POST 请求标头 Python 发送 x-api-key
【发布时间】:2020-08-12 17:54:56
【问题描述】:

我遇到了一个问题:

#Write a script that uses a web API to create a social media post.
#There is a tweet bot API listening at http://127.0.0.1:8082, GET / returns basic info about the API.
#POST / with x-api-key:tweetbotkeyv1 and data with user tweetbotuser and a status-update of alientest.

我的代码响应说我没有提供 x-api-key,但它在标题中。我的代码:

#
# Tweet bot API listening at http://127.0.0.1:8082.
# GET / returns basic info about api. POST / with x-api-key:tweetbotkeyv1
# and data with user tweetbotuser and status-update of alientest
#

import urllib.parse
import urllib.request

data = urllib.parse.urlencode({ 
  
  "x-api-key": "tweetbotkeyv1",
  "connection": "keep-alive",
  "User-agent": "tweetbotuser",
  "status-update": "alientest"
})


url = "http://127.0.0.1:8082"

data = data.encode("ascii")
with urllib.request.urlopen(url, data) as f:
    print(f.read().decode("utf-8"))

返回:

{"success": "false", "message":"x-api-key Not provided", "flag":""}

标题有问题吗?

【问题讨论】:

  • data 字典应作为请求发送headers,而不是data。由于urllib.request.urlopen 不直接支持标头,请改用Request 对象,或者(甚至更好)使用python requests(不是基本python 库的一部分,必须通过pip 或等效方式安装)

标签: python python-3.x post python-3.8 request-headers


【解决方案1】:

url、参数和header必须严格按照顺序提交: urllib.request.Request(url, post_param, header) 结果将是:{"success": "true", "message":"Well done", "flag":"<the flag will be show here>"}

这是可行的解决方案

import urllib.parse
import urllib.request

url = "http://127.0.0.1:8082/"
header={"x-api-key" : 'tweetbotkeyv1'}
post_param = urllib.parse.urlencode({
                    'user' : 'tweetbotuser',
           'status-update' : 'alientest'
          }).encode('UTF-8')

req = urllib.request.Request(url, post_param, header)
response = urllib.request.urlopen(req)

print(response.read())

【讨论】:

  • 非常感谢!
  • @Ollie 别担心
  • 嗨,我没有“用户”和“状态更新”信息。我该怎么办
  • @Clegane 代码应该可以正常工作;也许你正在做一些不同的事情?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-16
  • 2019-10-19
  • 1970-01-01
  • 2016-03-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多