使用 POST 请求标头发送 x-api-key Python

Oll*_*lie 5 python post request-headers python-3.x python-3.8

我遇到了一个问题,其中指出:

#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.
Run Code Online (Sandbox Code Playgroud)

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

#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.
Run Code Online (Sandbox Code Playgroud)

返回:

{"success": "false", "message":"x-api-key Not provided", "flag":""}
Run Code Online (Sandbox Code Playgroud)

标题有问题吗?

小智 5

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())
Run Code Online (Sandbox Code Playgroud)