python解析http响应(字符串) [英] python parse http response (string)

查看:1545
本文介绍了python解析http响应(字符串)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using python 2.7 and I want to parse string HTTP response fields which I already extracted from a text file. What would be the easiest way? I can parse requests by using the BaseHTTPServer but couldn't manage to find something for the responses.

我所拥有的响应非常标准,并采用以下格式

The responses I have are pretty standard and in the following format

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 的设计并非由用户直接实例化。

You might find this useful, keep in mind that HTTPResponse wasn't designed to be "instantiated directly by user."

另请注意,响应字符串中的内容长度标头可能不再有效(这取决于您获取这些响应的方式)这只是意味着对HTTPResponse.read()的调用需要大于为了得到这一切的内容。

Also note that the content-length header in your response string may not be valid any more (it depends on how you've aquired these responses) this just means that the call to HTTPResponse.read() needs to have value larger than the content in order to get it all.

这个例子是特定于python v2的,在v3-ish中,StringIO和httplib的导入位置已经改变。

This example is python v2 specific, in v3-ish the import locations for StringIO and httplib have changed.

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解析http响应(字符串)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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