我正在嘗試使用相當長(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: %s\nheaders:\n%s\n\nbody:\n%s\n", 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 umCnRXzQveOrSCAgfYWsfNSQDKGRvsTLnwCAWuVofumJPIhJQgQibpVJPQzqjncqjDbbHVjHidOJievmATjRexUPtVtke zuMaifyNkPiMPJwwoofurbMJyueoKKdnDuTUxhTrryuuMSUYhoRjV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TanTIhkoPUzDCjdaEslDXCqcaCwjIUKJMEiileCiIGASLyFYFLkKBHepbn dgmzeJQqEKycchmquNLGoVTJRPPwFBBRyzoEXylieyAUihLHHulYFJIWKXayiwkqIWjPKxmHaHUWanrzMbiHaMYdubXxk YAANJbNKvIWjZhheFMSOeIPogikXHTspixWKdFTZWWOKqsahTkFKJzrmUtBtqoYlXSjBErsbkbzJOtuXAeXHbKZsekmmU ohgOAdwaTVJgQLsYRIzIHnhErjKYEViADXfdXncenufRJDmAkEcjpqpxmFKdQmtqKwlUskVtgBAeVwnOTxdUnucxOcdyD uHoWAntZculQybCDYDEuqnzzjRklcGgAsNkyogLeZCRDSNWhQJCEQoiSChtAFWpmmzAjlhEDOnTzJyIUCzdbbPjhuDynk AuCggemjZIuisiVqgtJirqrbQeFlWckKVWsjIURcpeyGhQXzcQBQraqMJgBUafQyJiCcOefBrvwJOqyARmUZnunpwkBlD ytgwnwbBhdTUfyfUYeJjbDMDKiIYSOcyosmZvINlUYUuPhkkyojtYOzYtSFCdwTwxFJcqCDOTxyalYkvNYDvuaQKFwWIQ fkQAXiaoDQYREuhyntQBDCJohSqcdjZntuwgOVCvOPyJYMSNzksVDx Content-Length: 11 Body: hello world
以上是請求模組是否會截斷標頭?的詳細內容。更多資訊請關注PHP中文網其他相關文章!