Отправьте x-api-ключ с заголовком запроса POST Python - PullRequest
1 голос
/ 28 апреля 2020

У меня возникла проблема, которая гласила:

#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, но он есть в заголовке. Мой код:

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

Что-то не так с заголовком?

1 Ответ

1 голос
/ 30 апреля 2020

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())
...