杰瑞科技汇

Python如何发送自定义HTTP请求头?

Of course! The term "sendheader" in Python is most commonly associated with a specific library for sending email, but it can also refer to the general concept of sending HTTP headers. I'll cover both.

Python如何发送自定义HTTP请求头?-图1
(图片来源网络,侵删)

The sendheader Library (For Sending Email)

The most direct answer to "python sendheader" is the sendheader library, which is part of Python's standard library. It's a low-level module for constructing and sending email messages with headers.

Key Point: You will almost never use sendheader directly. It's a helper for higher-level modules like smtplib (for sending) and email (for constructing messages). The modern, recommended way to send email is with the smtplib and email libraries.

How to Use sendheader (Conceptual)

sendheader works by taking a file-like object (for example, a socket connected to an SMTP server) and a generator that yields header lines. It then formats these headers correctly according to RFC standards and writes them to the file-like object.

Here's a conceptual example to show how it fits into the process:

Python如何发送自定义HTTP请求头?-图2
(图片来源网络,侵删)
import sendheader
import smtplib
from email.message import EmailMessage
# 1. Create the email message content (body)
body = "This is the body of my email.\nIt has two lines."
# 2. Create a generator that yields the header lines
#    This is what sendheader expects
def header_generator():
    yield ("From", "sender@example.com")
    yield ("To", "recipient@example.com")
    yield ("Subject", "Test Email using sendheader")
    yield ("", "") # An empty header signifies the end of headers
# 3. Connect to an SMTP server (using a real server or a local one like MailHog)
#    For this example, we'll use a dummy socket to show the process.
#    In a real scenario, you would use smtplib.SMTP().
try:
    # Replace with your SMTP server details
    # with smtplib.SMTP('localhost', 1025) as server: # Example for MailHog
    #     server.sendmail("sender@example.com", "recipient@example.com", body)
    # This part would use the headers from our generator.
    # Let's simulate what sendheader does internally.
    # It takes a file-like object (our dummy socket) and the header generator.
    print("--- Simulating sendheader's output ---")
    # In a real app, you would pass a socket connection here.
    # For demonstration, we'll just print the formatted headers.
    # The sendheader module does the following:
    # for name, value in header_generator():
    #     if name == "":
    #         break # End of headers
    #     print(f"{name}: {value}") # This is the formatted line
    # Modern approach using the 'email' library (Recommended):
    msg = EmailMessage()
    msg['From'] = "sender@example.com"
    msg['To'] = "recipient@example.com"
    msg['Subject'] = "Test Email using email library"
    msg.set_content(body)
    # Now, to send it, you would use smtplib
    # with smtplib.SMTP('localhost', 1025) as server:
    #     server.send_message(msg)
    print("\n--- Modern 'email' library output ---")
    # The 'email' library handles header formatting for you.
    # When you call server.send_message(msg), it converts the message
    # into the correct format, including headers and body.
    print(msg.as_string())
except Exception as e:
    print(f"An error occurred: {e}")

Conclusion on sendheader: It's a low-level building block. For any practical email-sending task, use the smtplib and email libraries together.


Sending HTTP Headers (More Common Task)

When people talk about "sending headers," they are most often referring to HTTP headers, which are sent when making web requests (e.g., to a REST API). This is a very common task in Python.

The best library for this is requests. It's simple, powerful, and the de-facto standard for HTTP in Python.

Using the requests Library

You can send headers using the headers argument in functions like requests.get(), requests.post(), etc. The headers should be a dictionary.

Python如何发送自定义HTTP请求头?-图3
(图片来源网络,侵删)

Example: Sending a User-Agent and an Authorization header

This is a very common pattern when interacting with APIs.

import requests
# The URL of the API endpoint
url = "https://api.github.com/user"
# The headers you want to send
# It's good practice to set a custom User-Agent
headers = {
    "User-Agent": "MyCoolPythonApp/1.0",
    "Accept": "application/vnd.github.v3+json" # Ask for a specific API version
}
# If the API requires authentication, you might send an API key in the header
# headers["Authorization"] = "token YOUR_GITHUB_API_TOKEN"
try:
    # Make the GET request, passing the headers
    response = requests.get(url, headers=headers)
    # Raise an exception if the request was unsuccessful (e.g., 404, 500)
    response.raise_for_status()
    # Print the response data
    print("Status Code:", response.status_code)
    print("Response Headers:")
    print(response.headers) # The headers received from the server
    print("\nResponse Body (JSON):")
    print(response.json()) # Parse the JSON response
except requests.exceptions.HTTPError as errh:
    print(f"Http Error: {errh}")
except requests.exceptions.ConnectionError as errc:
    print(f"Error Connecting: {errc}")
except requests.exceptions.Timeout as errt:
    print(f"Timeout Error: {errt}")
except requests.exceptions.RequestException as err:
    print(f"Oops: Something Else: {err}")

Alternative: The http.client Module (Standard Library)

If you cannot use external libraries like requests, you can use Python's built-in http.client. It's more verbose but gives you a good understanding of the underlying process.

import http.client
import json
# For this example, we'll use the public httpbin.org service
# which is designed for testing HTTP requests.
host = "httpbin.org"
path = "/headers"
# Create a connection object
# For HTTPS, you would use http.client.HTTPSConnection
conn = http.client.HTTPConnection(host)
# Define the headers you want to send
headers_to_send = {
    "User-Agent": "MyStandardLibraryApp/1.0",
    "X-Custom-Header": "This is a custom value"
}
try:
    # Make the request
    # The body can be None for a GET request
    conn.request("GET", path, headers=headers_to_send)
    # Get the response from the server
    response = conn.getresponse()
    print(f"Status Code: {response.status}")
    print("Response Headers:")
    for header, value in response.getheaders():
        print(f"  {header}: {value}")
    # Read the response body
    data = response.read().decode('utf-8')
    print("\nResponse Body:")
    print(json.dumps(json.loads(data), indent=2)) # Pretty print the JSON
finally:
    # Always close the connection
    conn.close()

Summary

Context Tool/Library When to Use Example
Email Headers sendheader (low-level) Almost never. It's an internal helper. sendheader.send(socket, header_generator)
Email Headers smtplib + email (high-level) The standard way to send email. msg['From'] = '...'
HTTP Headers requests (3rd party) The recommended way. Simple, powerful, and easy to use. requests.get(url, headers={'User-Agent': '...'})
HTTP Headers http.client (standard library) When you can't use external libraries. More verbose. conn.request("GET", path, headers={'...'})

For 99% of cases, you'll want to use:

  • smtplib and email for sending email.
  • requests for making HTTP requests with custom headers.
分享:
扫描分享到社交APP
上一篇
下一篇