당신은 HTTPResponse이되도록 설계되지 않았 음을 명심,이 유용한를 찾을 수 있습니다 "사용자가 직접 인스턴스화."
응답 문자열의 content-length 헤더가 더 이상 유효하지 않을 수도 있습니다 (이 응답을 얻은 방법에 따라 다름) 이는 HTTPResponse.read()에 대한 호출이 value 모든 것을 얻으려면 콘텐츠보다 커야합니다.
이 예제는 Python v2에만 해당되며 v3-ish에서는 StringIO 및 httplib의 가져 오기 위치가 변경되었습니다.
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
이것은 정말로 내가 필요한 트릭처럼 보입니다. 아마 내 간단한 목적을 위해 regexes를 사용하여 내 길을 일할 수 있지만 HTTPResponse를 사용하면 훨씬 더 정확하다고 느낀다. 매우 감사합니다. –
후속 조치로서 테스트를 거쳤으며 그렇습니다. 이는 내가 원하는 것을 수행합니다. –
하지만 연결이 지속되면 어떻게 될까요? 이 솔루션을 사용하여 여러 헤더/본문을 파싱 할 수 있습니까? 이 대답하지 않은 질문의 예와 같은 것 : http://stackoverflow.com/questions/34786880/multiple-response-parsing-in-python?lq=1 – sajjadG