【问题标题】:Separating URL from http request将 URL 与 http 请求分开
【发布时间】:2010-09-08 10:07:48
【问题描述】:

我正在学习 Python 语言。我想了解拆分HTTP请求

GET /en/html/dummy.php?name=MyName&married=not+single &male=yes HTTP/1.1

Host: www.explainth.at
User-Agent: Mozilla/5.0 (Windows;en-GB; rv:1.8.0.11) Gecko/20070312 Firefox/1.5.0.11
Accept: text/xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://www.explainth.at/en/misc/httpreq.shtml

我想把GET和Host后面的部分(粗体)..

GET /en/html/dummy.php?name=MyName&married=not+single &male=yes HTTP/1.1

主持人:www.explainth.at

如何实现?

【问题讨论】:

    标签: python twisted


    【解决方案1】:

    不清楚您为什么要这样做,上下文或目标是什么,或者这些数据是如何到达您的程序的。但是,Python 在其字符串类型上支持许多有用的字符串操作。因此,如果您有一个包含所有这些文本的字符串,那么您可能会发现 splitlines 方法以及一些列表切片很有用:

    s = """\ ... GET /en/html/dummy.php?name=MyName&married=not+single &male=yes HTTP/1.1 ... 主持人:www.explainth.at ... 用户代理:Mozilla/5.0 (Windows;en-GB; rv:1.8.0.11) Gecko/20070312 Firefox/1.5.0.11 ...接受:text/xml,text/html;q=0.9,text/plain;q=0.8,image/png,/;q=0.5 ……“”“ s.splitlines()[:2] ['GET /en/html/dummy.php?name=MyName&married=not+single &male=yes HTTP/1.1', '主机:www.explainth.at']

    当然,如果您正在编写任何类型的真正 HTTP 服务器软件,那么这可能不是正确的方法(在如此低的级别上操作几乎为零,如果您需要的话,几乎可以肯定想要编写或重用真正的 HTTP 解析器)。所以你可能想问一个更精确的问题。

    【讨论】:

      【解决方案2】:

      您必须将 HTTP 请求拆分为 \r\n 字节。 (窗口上的换行符)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多