Python's Web Module learning--Httplib

Source: Internet
Author: User
Tags prefetch throw exception


1 httplib Introduction

Httplib is a client implementation of the HTTP protocol in Python that can be used to interact with the HTTP server

Httplib is a relatively low-level HTTP request module, which has a special packaging module, such as Urllib built-in modules, Goto and other third-party modules, but the higher the package is not flexible, such as the Urllib module in the request error will not return the contents of the results page, only the header information, For some scenarios where it is necessary to detect the return value of an error request, this module is used.

Httplib implements the client protocol for HTTP and HTTPS, which is generally not used directly, and uses its HTTP and HTTPS implementations in the Python's higher-level encapsulation module (URLLIB,URLLIB2). Where HTTPS requires the socket to compile SSL support. The HTTP class is only compatible with python1.5.2 and previous versions and is not recommended for use.

2 httplib Detailed

Here's a look at Httplib common classes

2.1 class Httplib. Httpconnection

There are two common ways of httpconnection classes:

1 httpconnection

Class Httplib. Httpconnection (host[,port[, strict[, timeout[, source_address]]) Usage: This class is used to create a request link parameter for an HTTP type: Host: Requested server host, cannot take HT tp://Opening port: Server Web Service Port strict: whether to strictly check the status line of the request, that is, the http1.0/1.1 protocol version of the line, that is, the first line of the request, the default is False, True when the check error will throw exception timeout: a single time please The time-out is not returned by default using the global timeout within the Httplib module: The Httpconnection class will instantiate and return an Httpconnection object in detail: The Httpconnection instance represents the transaction with the HTTP server. The delivery host and optional port number are required for instantiation. If there is no port number, try to extract from the host string in host:port format and use the default HTTP port (80) if the fetch fails. The parameter strict defaults to False, indicating that the status line cannot be http/when the state line cannot be resolved 1.0 or 1.1 does not throw a Badstatusline exception when parsing, the optional parameter, timeout, indicates how many seconds to block after the timeout, if not given the default use of the global timeout setting. An optional parameter, source_address, represents the source address (host, port) of the HTTP.

2 Httpsconnection

Class Httplib.    Httpsconnection (host[, port[, key_file[,cert_file[, strict[, timeout[, source_address] []]]) Usage: This class is used to create a request link parameter for an HTTPS type: Key_file: A private key file that contains the PEM format cert_file: A certificate file that contains PEM format other: The other is returned with the HTTP parameter: also returns a Httpsconnect Ion Object Note: To create an HTTPS link, you must ensure that the underlying socket module is a compile mode that supports SSL, that is, the switch of the compile-time SSL option is open: Httpconnection subclass, use SSL to communicate with secure server. The default port is 443. Key_file is the file name that contains the PEM-formatted private key. Cert_file is a certificate chain file in PEM format.

Attached code:

HTTP:

>>> import httplib>>> conn =httplib. Httpconnection (' www.baidu.com ') >>> conn = Httplib. Httpconnection (' www.baidu.com:80 ') >>> conn =httplib. Httpconnection (' www.baidu.com ', ' up ') >>> Conn =httplib. Httpconnection (' www.baidu.com ', ' up ', True) >>> Conn =httplib. Httpconnection (' www.baidu.com ', ' up ', true,10)

Error Example:

>>> Conn =httplib. Httpconnection (' www.baidu.com:80 ', true,10)

HTTPS :

>>> conn = Httplib. Httpsconnection (' www.baidu.com ', 443,key_file,cert_file,true,10)

The following is a method for the Httpconnection class

2.1.1 Httpconnection.request ()

Httpconnection.request (method, url [, body [, headers]]) usage: Calling the request method will send the requested parameter to the server: method: The requested way, such as ' GET ', ' PO ST ', ' HEAD ', ' PUT ', ' DELETE ' and other URLs: the requested page path. such as: '/index.html ' body: Request whether the data, the parameter is a dictionary headers: the request is the lead information, the parameter is a dictionary, but the name of the key is the specified HTTP header keyword returned: no return, in fact, is relative to the service to send the data, but there is no Rear return

Attached code:

>>> import Httplib>>>conn=httplib. Httpconnection (' www.baidu.com ', 80,false,10) >>> conn.request (' Get ', '/', ' ', ' {' user-agent ': ' Test '})

2.1.2 httpconnection.getresponse ()

Description: Gets an HTTP response object that is equivalent to performing the last 2 return returns: HttpResponse object (used below)

Attached code:

>>> Import httplib>>> conn=httplib. Httpconnection (' www.baidu.com ', 80,false,10) >>> conn.request (' Get ', '/', ' ', ' {' user-agent ': ' Test '}) > >>res = Conn.getresponse ()

2.1.3 httpconnection. Connect()

After the object is created, connect to the specified server

2.1.4 httpconnection. Close()

Close the connection to the server

Attached code:

>>> Import httplib>>> conn=httplib. Httpconnection (' www.baidu.com ', 80,false,10) >>> conn.request (' Get ', '/', ' ', ' {' user-agent ': ' Test '}) > >> res = Conn.getresponse () >>>conn.close ()

2.1.5 httpconnection.set_debuglevel (level)

Sets the level of height. The default value of the parameter level is 0, which means that no debug information is output


2.2 Class Httplib. HttpResponse

HttpResponse represents the server's response to a client request. It is often created by calling Httpconnection.getresponse (), the class returned after the instance is connected successfully, and cannot be instantiated by the user.

It has the following methods and properties:

2.2.1 Httpresponse.read ([Amt])

Description: Gets the content part of the HTTP response, the Web source prototype: BODY = Res.read ([Amt]) Amt: reads a specified length of characters, defaults to NULL, which reads all content returned: Web content string

Gets the message body of the response. If the request is a normal Web page, then the method returns the HTML of the page. Optional Parameters Amt represents the data from the response stream that reads the specified bytes.

Attached code:

>>>conn=httplib. Httpconnection (' www.baidu.com ', 80,false,10) >>> conn.request (' GET ', ') >>> res = Conn.getresponse ( ) >>>res.read () #下面的为网页信息 ' <! DOCTYPE html><!--statusok-->\r\n

2.2.2 Httpresponse.getheader (name[, default])

Gets the specified response header. The name represents the header field (Headerfield) name, and the optional parameter default is returned as the default if the header domain name does not exist.

2.2.3 Httpresponse.getheaders ()

Get all the response header content, is a tuple list [(Name,value), (name2,value2)]


Attached code:

>>>res.getheaders () [(' Content-length ',  ' 14613 '),  (' bdqid ', ' 0x9d3801010001675e '),  (' Set-cookie ', ' baiduid=9acdf7c2df8c2ea720cbd97636829343:fg=1; expires=thu, 31-dec-37 23:55:55gmt;  max-age=2147483647; path=/; domain=.baidu.com,BIDUPSID=9ACDF7C2DF8C2EA720CBD97636829343;  Expires=thu, 31-dec-37 23:55:55 gmt;max-age=2147483647; path=/; domain=.baidu.com,  pstm=1436858070; expires=thu,31-dec-37 23:55:55 gmt; max-age=2147483647; path=/ ;  domain=.baidu.com,bdsvrtm=0; path=/'),  (' accept-ranges ',  ' bytes '),  (' Vary ',  ') Accept-encoding '), (' Bduserid ',  ' 0 '),  (' Server ',  ' bws/1.1 '),  (' last-modified ',  ' Wed,  03 sep 201402:48:32 gmt '),  (' Connection ',  ' keep-alive '),  (' X-ua-compatible ',  ' ie=edge,chrome=1 '), (' pragma ',  ' no-cache '),  (' Cache-control ',  ' No-cache '),  (' Date ' ,  ' tue, 14 jul2015 07:14:30 gmt '),  (' P3P ',  ' cp= " oti dsp cor iva our  IND COM  "'), (' Content-type ',  ' text/html '),  (' Bdpagetype ',  ' 1 ')]

2.2.4 Httpresponse.msg

Gets all the response header information. Contains the mimetools of the response header. Message instance

>>>res.msg

2.2.5 httpresponse.msg

Gets the version of the HTTP protocol used by the server. 11 means http/1.1;10 represents http/1.0

>>> res.version11

2.2.6 Httpresponse.status

Gets the status code of the response. Example: 200 indicates a successful request

>>> res.status200

2.2.6 Httpresponse.reason

Returns a description of the result of the server processing request. Generally "OK"

>>> Res.reason ' OK '

2.3 Class Httplib. Httpmessage

The Httpmessage instance is used to hold the HTTP response header. It uses Mimetools. The message class is implemented and provides a tool function for handling HTTP headers. It is not directly instantiated by the user. cannot be instantiated by the user.

2.4 Exceptions

Exception Httplib. HttpException

The base class for other exceptions in this module, exception subclasses. The following class defaults to the immediate subclass of the class.

    • Httplib. notconnected

    • Httplib. Invalidurl

    • Httplib. Unknownprotocol

    • Httplib. Unknowntransferencoding

    • Httplib. Unimplementedfilemode

    • Httplib. Incompleteread

    • Httplib. Improperconnectionstate

    • Httplib. Cannotsendrequest

A subclass of Improperconnectionstate.

    • Httplib. Cannotsendheader

A subclass of Improperconnectionstate.

    • Httplib. Responsenotready

A subclass of Improperconnectionstate.

    • Httplib. Badstatusline

The HTTP status code returned by the server is not known when it is generated.

2.5 Constants and class variables

    • Httplib. The default port for the HTTP_PORT:HTTP protocol, constant 80.

    • Httplib. The default port for the HTTPS_PORT:HTTPS protocol, constant 443.

    • Status constants: See Http://docs.python.org/2/library/httplib.html

    • Httplib.responses: Maps the HTTP1.1 status code to the dictionary of the name of the consortium.




This article is from "a struggling small operation" blog, please be sure to keep this source http://yucanghai.blog.51cto.com/5260262/1697732

Python's Web Module learning--Httplib

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.