📜  httplib python (1)

📅  最后修改于: 2023-12-03 15:31:20.323000             🧑  作者: Mango

Python's HTTP client library - httplib

Python's httplib module provides a comprehensive suite of classes and methods for implementing HTTP requests and responses. It is an essential library for web developers and network engineers working with Python.

Table of Contents
HTTP Requests

The httplib library provides several methods for sending HTTP requests such as GET, POST, PUT, DELETE, etc. To send an HTTP request using httplib, you first need to create an HTTPConnection object and then invoke the respective request method.

import httplib

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

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

response = conn.getresponse()

print response.status, response.reason

data = response.read()

conn.close()
HTTP Responses

The httplib library provides an HTTPResponse class for handling HTTP responses. An HTTPResponse object represents the server response to an HTTP request.

import httplib

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

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

response = conn.getresponse()

print response.status, response.reason

for header in response.getheaders():
    print header[0], header[1]

data = response.read()

conn.close()
HTTP Connections

The httplib library provides an HTTPConnection class for creating an HTTP connection to a specified host and port.

import httplib

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

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

response = conn.getresponse()

data = response.read()

conn.close()
HTTP Authentication

The httplib library provides support for HTTP Basic Authentication. To send an authenticated request, include the Authorization header in the HTTP request.

import httplib

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

username = "username"
password = "password"

headers = {"Authorization": "Basic " + base64.b64encode(username + ":" + password)}

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

response = conn.getresponse()

data = response.read()

conn.close()
HTTPS

The httplib library can also be used to send HTTPS requests. To send an HTTPS request, create an HTTPSConnection object instead of an HTTPConnection object.

import httplib

conn = httplib.HTTPSConnection("www.example.com")

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

response = conn.getresponse()

data = response.read()

conn.close()
Example Usage
import httplib

conn = httplib.HTTPSConnection("www.example.com")

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

response = conn.getresponse()

if response.status == 200:
    data = response.read()
    print data

conn.close()

This code sends an HTTPS request to www.example.com for the index.html page. It then reads the response and prints the data to the console.