我爱编程

【18-04-15】Python模拟HTTP请求

2018-04-15  本文已影响0人  isla

简易代码:

import httplib

def main():

        conn=httplib.HTTPConnection("www.baidu.com")

        conn.request("GET","/index.html")

        resp=conn.getresponse() #The method return a HTTPResponse instance

        headers=resp.getheaders()

        content=resp.read()

        print headers

        print

        print content

if __name__=='__main__':

        main()

1. class HTTPConnection(host[, port[, strict[, timeout[, source_address]]]])

host:主机名

port:端口号,如此处未传递端口号,则会在host中提取,格式为host:port。如果前两者都未指明,默认值80。

strict:True/False.当为True时,如果状态行(status line)不能被解析为有效的HTTP/1.0 or 1.1状态行,则抛出BadStatusLine异常(exception)

timeout:超时时间

source_address: Python官网原文:

The optional source_address parameter may be a tuple of a (host, port) to use as the source address the HTTP connection is made from.

可选参数。这个参数可以是一个元组,用于给出HTTP连接请求的源地址(source address)

部分类成员函数:

close(self): 关闭连接

getresponse(self,buffering=False): 获取服务器响应,返回一个HTTPResponse对象实例

request(self, method, url, body=None, headers={}):向服务器发送请求

这里用到计网:

method:请求方法,例如GET POST HEAD PUT DELETE

url:请求的对象路径,例如/index.html

body:对应计网书中的“实体体”(entity body),即请求所带的数据,是一个字典类型对象

headers:对应计网书中的“首部行”(header line),字典类型对象

2. class HTTPResponse(sockdebuglevel=0strict=0)

Class whose instances are returned upon successful connection. Not instantiated directly by user.

New in version 2.0.

用户不直接实例化,通过HTTPConnection的方法getresponse()获得实例

部分成员函数:

read([amt]):读取并返回服务器响应报文中的“实体体”(entity body),例如请求了一个网页文件(html),则获得源码。可选参数amt指定获取源码的长度。

getheaders():返回一个元组列表,记录响应报文中的首部行(header line)

回忆计网:

HTTP响应报文分为“状态行” “首部行” 首部行后接一个空行 空行后是“实体体”(entity body)

“状态行”的协议版本 状态码 状态信息 在这里被分成了三部分 由三个成员对象分别存储:

协议版本--version 状态码--status 状态信息--reason


--未完待续--

上一篇 下一篇

猜你喜欢

热点阅读