In-depth understanding of the http. client module in Python3, python3http. client

Source: Internet
Author: User

In-depth understanding of the http. client module in Python3, python3http. client

Introduction to the http Module

The http package in Python3 contains several modules used to develop the HTTP protocol.

  • Http. client is an underlying HTTP client, which is used by the higher-level urllib. request module.
  • Http. server contains the basic HTTP server class based on socketserver.
  • Http. cookies implement cookie Status Management
  • Cookie-related http. cookiejar

The http module also defines a series of HTTP status codes.

The HTTPStatus class is added to Python 3.5.

>>> from http import HTTPStatus>>> HTTPStatus.OK<HTTPStatus.OK: 200>>>> HTTPStatus.OK == 200True>>> http.HTTPStatus.OK.value200>>> HTTPStatus.OK.phrase'OK'>>> HTTPStatus.OK.description'Request fulfilled, document follows'>>> list(HTTPStatus)[<HTTPStatus.CONTINUE: 100>, <HTTPStatus.SWITCHING_PROTOCOLS: 101>, ...]

The specific HTTP status code and the corresponding instructions can be found in the Python official documentation: https://docs.python.org/3/library/http.html

Http. client Module

The http. client module defines classes for implementing http and https client.

This module is usually not used directly. Instead, it uses the encapsulated urllib. request module to process URLs.

Constant

Constants in the http module:

1. http. client. HTTP_PORT

Default http port number, always port 80

2. http. client. HTTPS_PORT

Default https port number, which is always port 443

3. http. client. responses

Maps the HTTP 1.1 Status Code to the W3C name dictionary.

For example:

http.client.responses[http.client.NOT_FOUND] is 'Not Found'

Basic Class

HTTPConnection class

http.client.HTTPConnection(host, port=None, [timeout, ]source_address=None)

The HTTPConnection instance indicates the transaction with the HTTP server.

When instantiating HTTPConnection, you should pass a host and an optional port number. If no port is passed and the host string is in the form of host: port, the port value is extracted; otherwise, the default port 8-port is used.

If the optional timeout parameter is specified, the blocking operation times out after the specified time. If not, the default global timeout setting is used.

The optional parameter source_address should be in the form of host and port, used as the source address of the HTTP connection.

The sample code is as follows:

>>> h1 = http.client.HTTPConnection('www.python.org')>>> h2 = http.client.HTTPConnection('www.python.org:80')>>> h3 = http.client.HTTPConnection('www.python.org', 80)>>> h4 = http.client.HTTPConnection('www.python.org', 80, timeout=10)

Source_address is added in version 3.2.

The strict parameter is removed in version 3.4.

HTTPSConnection class

HTTPSConnection(host, port=None, key_file=None, cert_file=None, [timeout, ]source_address=None, *, context=None, check_hostname=None)

HTTPSConnection is a subclass of HTTPConnection. You can use SSL to contact the security server.

The default port is 443. If context is specified, it must be an ssl. SSLContext instance to describe different SSL options.

Key_file and cert_file have been discarded and replaced by ssl. SSLContext. load_cert_chain (). Alternatively, use ssl. create_default_context () to select the CA certificate trusted by the system.

The check_hostname parameter is also discarded. Use the ssl. SSLContext. check_hostname attribute of context.

HTTPResponse class

class http.client.HTTPResponse(sock, debuglevel=0, method=None, url=None)

Once the connection is successful, the instance will be returned. The objects of this class cannot be directly instantiated by the user.

HTTPMessage class

The HTTPMessage instance holds the header returned from HTTP response.

Exception

HTTPException class

The subclass of the Exception class, which is also the base class of other Exception classes in the http module.
Other exceptions:

  • NotConnected
  • InvalidURL
  • UnknownProtocol
  • UnknownTransferEncoding
  • UnimplementedFileMode
  • IncompletedRead
  • ImproperConnectionState
  • BadStatusLine
  • Linw.long
  • CannotSendRequest
  • CannotSendHeader
  • ResponseNotReady
  • RemoteDisconnected

Class Method

HTTPConnection object Method

The HTTPConnection instance has the following methods:

1. HTTPConnection. request (method, url, body = None, headers = {})

Send a request to the server using the specified method and url link.

If the body part is specified, the body part is sent after the header part is sent. The body part can be a string, Byte object, file object, or Byte object iterator. Different body types correspond to different requirements.

The header parameter should be a ing of the HTTP header and a dictionary type.

If the header does not contain the Content-Length entry, it will be automatically added according to the body.

2. HTTPConnection. getresponse ()

The content returned by the server can be called only after the request is sent. An HTTPResponse instance is returned.

3. HTTPConnection. set_debuglevel (level)

Set the debugging level. The default debugging level is 0, which means no debugging output is available.

4. HTTPConnection. set_tunnel (host, port = None, headers = None)

Set the host and port of the HTTP Tunnel Link, which allows the connection to use the proxy server.

5. HTTPConnection. connect ()

Connect to the specified server. By default, if the client is not connected, this method is automatically called during request.

6. HTTPConnection. close ()

Close the link.

7. HTTPConnection. putrequest (request, selector, skip_host = False, skip_accept_encoding = False)

When the connection to the server is successful, call this method first.

The content sent to the server includes the request string, selector string, and HTTP Protocol version.

8. HTTPConnection. putheader (header, argument [,…])

Send the HTTP header to the server.

The content sent to the server includes the header, colon, space, and the first in the parameter list.

9. HTTPConnection. endheaders (message_body = None)

Send a blank row to the server to identify the end Of the header.

10. HTTPConnection. send (data)

Send data to the server.

It should be called after the endheaders () method and before the getresponse () method.

HTTPResponse object Method

The HTTPResponse instance contains the HTTP response returned from the server.

It provides methods to access the request header and body.

HTTPResponse is an iteratable object and can be declared using the with statement.

The HTTPResponse instance has the following methods:

1. HTTPResponse. read ([amt])

Read and return the body of response.

2. HTTPResponse. readinto (B)

Read the specified length len (B) and return to the buffer byte B.

Number of bytes read by the function

3. HTTPResponse. getheader (name, default = None)

Return the HTTP header value of the specified name. If no matched name value exists, the default None is returned. If multiple matching values exist, all values are returned, separated by commas.

4. HTTPResponse. getheaders ()

Returns all header information (header, value) in the form of tuples ).

5. HTTPResponse. fileno ()

6. HTTPResponse. msg

7. HTTPResponse. version.

HTTP Version

8. HTTPResponse. status

HTTP status code

9. HTTPResponse. reason

10. HTTPResponse. debuglevel

11. HTTPResponse. closed

If the value is True, the connection is closed.

Example

Import http. clientimport urllib, parser # Initialize an https link conn = http. client. HTTPSConnection ("www.python.org") # specify the request method and the request link address conn. request ("GET", "/doc/") # obtain the returned http responser1 = conn. getresponse () # HTTP status code print (r1.status, r1.reason) # HTTP header print (r1.getheaders () # body part print (r1.read () # If the connection is not closed, print the first 200 bytes of the output if not r1.closed: print (r1.read (200) # The connection can be re-requested after the connection is closed. close () # request a non-existent file or address conn. request ("GET", "/parrot. spam ") r2 = conn. getresponse () print (r2.status, r2.reason) conn. close () # use HEAD requests, but no data is returned. conn = http. client. HTTPSConnection ("www.python.org") conn. request ("HEAD", "/") res = conn. getresponse () print (res. status, res. reason) data = res. read () print (len (data) conn. close () # In the POST request, put the submitted data in the body section params = urllib. parse. urlencode ({'@ number': 12524,' @ type': 'issue ',' @ action': 'Show '}) # post request data, the Content-type field must be included to inform the Message Subject of the encoding method headers = {"Content-type": "application/x-www-form-urlencoded", "Accept ": "text/plain"} conn = http. client. HTTPConnection ("bugs.python.org") conn. request ("POST", "/", params, headers) response = conn. getresponse () # redirected print (response. status, response. reason) print (response. read (). decode ("UTF-8") conn. close ()

Summary

The above is all about this article. I hope this article will help you learn or use python. If you have any questions, please leave a message, thank you for your support.

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.