gpt4 book ai didi

python解析http响应(字符串)

转载 作者:太空狗 更新时间:2023-10-29 18:00:14 25 4
gpt4 key购买 nike

我正在使用 python 2.7,我想解析我已经从文本文件中提取的字符串 HTTP 响应字段。最简单的方法是什么?我可以使用 BaseHTTPServer 解析请求,但无法找到响应的内容。

我的回复非常标准,格式如下

HTTP/1.1 200 OK
Date: Thu, Jul 3 15:27:54 2014
Content-Type: text/xml; charset="utf-8"
Connection: close
Content-Length: 626

提前致谢

最佳答案

您可能会发现这很有用,请记住 HTTPResponse并非旨在“由用户直接实例化”。

另请注意,响应字符串中的内容长度 header 可能不再有效(这取决于您获取这些响应的方式)这仅意味着对 HTTPResponse.read() 的调用需要具有更大的值比内容更重要。

在python 2中可以这样运行。

from httplib import HTTPResponse
from StringIO import StringIO

http_response_str = """HTTP/1.1 200 OK
Date: Thu, Jul 3 15:27:54 2014
Content-Type: text/xml; charset="utf-8"
Connection: close
Content-Length: 626"""

class FakeSocket():
def __init__(self, response_str):
self._file = StringIO(response_str)
def makefile(self, *args, **kwargs):
return self._file

source = FakeSocket(http_response_str)
response = HTTPResponse(source)
response.begin()
print "status:", response.status
print "single header:", response.getheader('Content-Type')
print "content:", response.read(len(http_response_str)) # the len here will give a 'big enough' value to read the whole content

在python 3中,HTTPResponse是从http.client导入的,需要解析的response需要进行字节编码。根据从何处获取数据,这可能已经完成或需要显式调用

from http.client import HTTPResponse
from io import BytesIO

http_response_str = """HTTP/1.1 200 OK
Date: Thu, Jul 3 15:27:54 2014
Content-Type: text/xml; charset="utf-8"
Connection: close
Content-Length: 626

teststring"""

http_response_bytes = http_response_str.encode()

class FakeSocket():
def __init__(self, response_bytes):
self._file = BytesIO(response_bytes)
def makefile(self, *args, **kwargs):
return self._file

source = FakeSocket(http_response_bytes)
response = HTTPResponse(source)
response.begin()
print( "status:", response.status)
# status: 200
print( "single header:", response.getheader('Content-Type'))
# single header: text/xml; charset="utf-8"
print( "content:", response.read(len(http_response_str)))
# content: b'teststring'

关于python解析http响应(字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24728088/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com