请求模块是否会截断标头?

2024年 2月 22日 64.9k 0

请求模块是否会截断标头?

问题内容

我正在尝试使用相当长(1017 个字符)的承载令牌向我的 API 发出 POST 请求以进行授权。

无论我尝试什么,当我启动请求时,我都会收到一条错误消息,指出位置 512 中的 u2026 (水平省略号)无法使用“latin-1”编码进行编码。由于我找不到我指定的标头的任何问题(或省略号),我唯一的解释是请求模块在内部默默地截断了我的令牌。难道是这样吗?可以禁用吗?还有其他解决方法吗?

正确答案

不,它不会截断标头。您可以通过运行打印所有收到的请求的 localhost http 服务器来查看这一点。以下是使用 2000 个字符标记的示例。

# from https://gist.github.com/mdonkers/63e115cc0c79b4f6b8b3a6b797e485c7
from http.server import basehttprequesthandler, httpserver
import logging

class s(basehttprequesthandler):
def _set_response(self):
self.send_response(200)
self.send_header('content-type', 'text/html')
self.end_headers()

def do_post(self):
content_length = int(self.headers['content-length'])
post_data = self.rfile.read(content_length)
logging.info("post request,npath: %snheaders:n%snnbody:n%sn",
str(self.path), str(self.headers), post_data.decode('utf-8'))

self._set_response()
self.wfile.write("post request for {}".format(self.path).encode('utf-8'))

def run(server_class=httpserver, handler_class=s):
logging.basicconfig(level=logging.info)
server_address = ('', 8080)
httpd = server_class(server_address, handler_class)
try:
httpd.serve_forever()
except keyboardinterrupt:
pass
httpd.server_close()

if __name__ == '__main__':
run()

登录后复制

在本地主机上运行它,然后使用请求来发布请求:

import requests
import random
import string

token = ''.join(random.choices(string.ascii_letters, k=2000))
requests.request('post', 'http://localhost:8080', headers={'token': token}, body='hello world')

登录后复制

产生以下输出:

INFO:root:POST request,
Path: /
Headers:
Host: localhost:8080
User-Agent: python-requests/2.31.0
Accept-Encoding: gzip, deflate, br
Accept: */*
Connection: keep-alive
token: CrJlFIgJbvNdpTFPvkvCpaCPmugqMbjCUOYJaCCoibZdLfrEmLRDyxXiABGqHPTpkDYXznIWyVHwmThzBbzISh
umCnRXzQveOrSCAgfYWsfNSQDKGRvsTLnwCAWuVofumJPIhJQgQibpVJPQzqjncq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AcZxQYcwhUUbDwCyYbMSNmpGYaJlxeNUlcrLWXSrzAtAfblXtnC
UzpnOJVYIsGONvdZyJIDwGdbaXsGZtILdPFTanTIhkoPUzDCjdaEslDXCqcaCwjIUKJMEiileCiIGASLyFYFLkKBHepbn
dgmzeJQqEKycchmquNLGoVTJRPPwFBBRyzoEXylieyAUihLHHulYFJIWKXayiwkqIWjPKxmHaHUWanrzMbiHaMYdubXxk
YAANJbNKvIWjZhheFMSOeIPogikXHTspixWKdFTZWWOKqsahTkFKJzrmUtBtqoYlXSjBErsbkbzJOtuXAeXHbKZsekmmU
ohgOAdwaTVJgQLsYRIzIHnhErjKYEViADXfdXncenufRJDmAkEcjpqpxmFKdQmtqKwlUskVtgBAeVwnOTxdUnucxOcdyD
uHoWAntZculQybCDYDEuqnzzjRklcGgAsNkyogLeZCRDSNWhQJCEQoiSChtAFWpmmzAjlhEDOnTzJyIUCzdbbPjhuDynk
AuCggemjZIuisiVqgtJirqrbQeFlWckKVWsjIURcpeyGhQXzcQBQraqMJgBUafQyJiCcOefBrvwJOqyARmUZnunpwkBlD
ytgwnwbBhdTUfyfUYeJjbDMDKiIYSOcyosmZvINlUYUuPhkkyojtYOzYtSFCdwTwxFJcqCDOTxyalYkvNYDvuaQKFwWIQ
fkQAXiaoDQYREuhyntQBDCJohSqcdjZntuwgOVCvOPyJYMSNzksVDx
Content-Length: 11

Body:
hello world

登录后复制

以上就是请求模块是否会截断标头?的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论