Python 3 POST请求400错误

时间:2017-05-03 18:00:52

标签: python-3.x http curl post

我试图用urllib发送请求:

import urllib.request
import urllib.parse
from urllib.error import URLError, HTTPError

api_key = ""
base_url_string = 'URL'
values = {'api_key' : api_key}

user_agent = 'curl/7.47.0'
headers = {'Content-Type' : 'application/json',
           'User-Agent': user_agent,
           'Accept' : '*/*'}

data = urllib.parse.urlencode(values)
data = data.encode('ascii')
request = urllib.request.Request(url=base_url_string, data=data, headers=headers)

try:
    response = urllib.request.urlopen(request)
    json_response = json.loads(response.read().decode("utf-8"))

    for line in json_response:
        print(line)

except URLError as e:
    print(e)

并获取" HTTP错误400:错误请求"

curl -v -H "Content-Type: application/json" -d '{"api_key":""}' URL

工作正常。 我在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

您宣布application/json为内容类型。但您通过urllib.parse.urlencode()实际编码的是application/x-www-form-urlencoded。请尝试使用json.dumps()