使用具有多个标头的urllib进行POST请求会产生400错误的请求错误 [英] Making a POST request using urllib with multiple headers gives 400 Bad Request error

查看:70
本文介绍了使用具有多个标头的urllib进行POST请求会产生400错误的请求错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用过 requests 库,并且我知道如何使用它,但是我只需要使用标准库,因此,如果您不鼓励我使用,我将不胜感激.请求代替.

I have used requests library and I know how to work with it, but I need to work with standard library only, so I would appreciate if you don't encourage me to use requests instead.

我制作了一个处理POST请求的Flask服务器,然后从另一个脚本中调用 urllib 对flask服务器进行POST调用.我需要像在Postman中一样在正文中发送原始json.

I made a flask server that handles POST requests and then from a different script I call urllib to make POST calls to the flask server. I need to send a raw json in body just like we do in Postman.

烧瓶服务器

from flask import Flask, request

app = Flask(__name__)
@app.route('/random', methods=['POST'])
def random():
    if request.method == 'POST':
        if request.headers.get('Authorization') and request.headers.get('Content-Type') == 'application/json':
            print(request.get_json())
            return "Success"
        else:
            print(request.get_json())
            return "Bad request"

app.run(host='0.0.0.0', port=5000, debug=True)

Urllib客户端(保存为test.py)-

Urllib Client (saved as test.py) -

import urllib.request
import urllib.parse
d = {"spam": 1, "eggs": 2, "bacon": 0}
data = urllib.parse.urlencode(d)
data = data.encode()
req = urllib.request.Request("http://localhost:5000/random", data)
req.add_header('Content-Type', 'application/json')
req.add_header('Authorization', 12345)
with urllib.request.urlopen(req) as f:
    print(f.read().decode('utf-8'))

仅具有 Authorization 标头,我得到 Bad Request 作为输出,而在烧瓶服务器端上,json是 None .

With only Authorization header I get Bad Request as output and the json is None on the flask server side as expected.

仅使用Content-Type标头或两个标头,我都会收到此错误-

With ONLY Content-Type header OR both the headers I get this error -

Traceback (most recent call last):
  File "test.py", line 9, in <module>
    with urllib.request.urlopen(req) as f:
  File "C:\ProgramData\Anaconda3\lib\urllib\request.py", line 223, in urlopen
    return opener.open(url, data, timeout)
  File "C:\ProgramData\Anaconda3\lib\urllib\request.py", line 532, in open
    response = meth(req, response)
  File "C:\ProgramData\Anaconda3\lib\urllib\request.py", line 642, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\ProgramData\Anaconda3\lib\urllib\request.py", line 570, in error
    return self._call_chain(*args)
  File "C:\ProgramData\Anaconda3\lib\urllib\request.py", line 504, in _call_chain
    result = func(*args)
  File "C:\ProgramData\Anaconda3\lib\urllib\request.py", line 650, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 400: BAD REQUEST

整个过程很简单,但是我不明白为什么会这样,并且错误消息也无济于事.

The whole thing is simple enough, but I am not able to understand why is this happening and the error message doesn't help much either.

推荐答案

服务器在 request.get_json()中发生故障.只有当客户端发送两个标头时才发生这种情况,因为那是到达该行的时间.

The server is failing in request.get_json(). It's only happening when the client sends both headers because that's when it reaches this line.

要解决此问题,请更改客户端以将数据作为JSON发送:

To fix it, change the client to send the data as JSON:

import json            # <-- Import json
import urllib.request
import urllib.parse

d = {"spam": 1, "eggs": 2, "bacon": 0}
data = json.dumps(d)   # <-- Dump the dictionary as JSON
data = data.encode()
req = urllib.request.Request("http://localhost:5000/random", data)
req.add_header('Content-Type', 'application/json')
req.add_header('Authorization', 12345)
with urllib.request.urlopen(req) as f:
    print(f.read().decode('utf-8'))

我希望这对您有帮助

这篇关于使用具有多个标头的urllib进行POST请求会产生400错误的请求错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆