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

问题描述 投票:0回答:1

我被告知有一个问题:

#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":""}

标题有问题吗?

python python-3.x post python-3.8 request-headers
1个回答
0
投票

URL,参数和标题必须严格按照以下顺序提交: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())
© www.soinside.com 2019 - 2024. All rights reserved.