search

What is Httpx

Httpx is a Python library that provides a modern, easy-to-use HTTP client and server. Httpx works with Python's asynchronous framework and supports WebSocket and HTTP/2. Httpx offers excellent performance, security, and flexible configuration for a variety of different protocols, encodings, and authentication schemes.

Installing Httpx

Installing the Httpx library is very simple. Just run the following command using the pip package manager:

pip install httpx

If you are using Python 3.7 or earlier, you need to install Httpx's asynchronous dependency aiohttp.

You can install it by running the following command:

pip install httpx[aiohttp]

Sending HTTP requests

Sending HTTP requests using Httpx is very simple. Here is a simple example that uses Httpx to send a GET request:

import httpx

response = httpx.get('https://www.baidu.com')
print(response.status_code)
print(response.text)

In this example, we sent a GET request using the get method of Httpx. The requested URL is https://www.baidu.com. This method returns a Response object that we can use to access the response status code and response text.

Httpx supports many different HTTP methods, including GET, POST, PUT, DELETE, HEAD, and OPTIONS. You can use Httpx methods to send these requests.

Here are some examples:

import httpx

response = httpx.post('https://www.baidu.com', data={'key': 'value'})
response = httpx.put('https://www.baidu.com', data={'key': 'value'})
response = httpx.delete('https://www.baidu.com')
response = httpx.head('https://www.baidu.com')
response = httpx.options('https://www.baidu.com')

Each request in the above examples can be sent using Httpx methods. Most of these methods support passing parameters such as data, headers, and query parameters.

Send asynchronous HTTP requests

Httpx also supports asynchronous HTTP requests. The following is a simple example that uses Httpx to send an asynchronous GET request:

import httpx
import asyncio

async def get_request():
    async with httpx.AsyncClient() as client:
        response = await client.get('https://www.baidu.com')
        print(response.status_code)
        print(response.text)

asyncio.run(get_request())

In this example, we create an asynchronous function named get_request that uses the AsyncClient class of Httpx to send an asynchronous GET ask. In the asynchronous function, we use the async with statement to create an asynchronous client of Httpx. Creating the client this way ensures that the client is automatically closed after the request is completed. We then use the await keyword to asynchronously wait for the response and access the response status code and response text from the response object.

Similar to synchronous requests, Httpx's asynchronous client also supports many different HTTP methods.

Here are some examples:

import httpx
import asyncio

async def post_request():
    async with httpx.AsyncClient() as client:
        response = await client.post('https://www.baidu.com', data={'key': 'value'})
        print(response.status_code)
        print(response.text)

asyncio.run(post_request())

Setting request headers

When sending an HTTP request, you typically need to set request headers. Httpx allows you to set request headers by passing the headers parameter in the request method.

Here is an example:

import httpx

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}

response = httpx.get('https://www.baidu.com', headers=headers)
print(response.status_code)
print(response.text)

In this example, we set a request header named User-Agent using the headers parameter.

Set request parameters

Httpx allows you to set request parameters when sending an HTTP request.

Here are some examples:

import httpx

params = {'key1': 'value1', 'key2': 'value2'}

response = httpx.get('https://www.baidu.com', params=params)
print(response.status_code)
print(response.text)

In this example, we set two query parameters key1 and key2 using the params parameter.

Send Request Body

When sending POST, PUT, and DELETE requests, you typically need to include data in the request body. Httpx allows you to set data in the request body using the data parameter.

The following is an example:

import httpx

data = {'key': 'value'}

response = httpx.post('https://www.baidu.com', data=data)
print(response.status_code)
print(response.text)

In this example, we use the data parameter to set a request body parameter named key.

Send JSON data

Httpx allows you to send JSON data using the json parameter.

The following is an example:

import httpx

data = {'key': 'value'}

response = httpx.post('https://www.baidu.com', json=data)
print(response.status_code)
print(response.text)

In this example, we use the json parameter to set a JSON request body parameter named key.

Set timeout

When sending an HTTP request, you usually need to set a timeout. Httpx allows you to set a timeout using the timeout parameter.

Here is an example:

import httpx

response = httpx.get('https://www.baidu.com', timeout=5)
print(response.status_code)
print(response.text)

In this example, we set a timeout of 5 seconds using the timeout parameter.

Error handling

Httpx can throw a variety of different types of exceptions to help you diagnose and solve problems. Here are some common exceptions:

  • httpx.HTTPError: Raised when an HTTP error occurs.

  • httpx.RequestError: Raised when a request error occurs.

  • httpx.NetworkError: Raised when a network error occurs.

  • httpx.TimeoutException: Raised when a timeout occurs.

When handling these exceptions, you can use try/except statements to catch the exception and take appropriate action. Here is an example:

import httpx

try:
    response = httpx.get('https://www.baidu.com')
    response.raise_for_status()
except httpx.HTTPError as http_error:
    print(f'HTTP error occurred: {http_error}')
except httpx.RequestError as request_error:
    print(f'Request error occurred: {request_error}')
except httpx.NetworkError as network_error:
    print(f'Network error occurred: {network_error}')
except httpx.TimeoutException as timeout_error:
    print(f'Timeout error occurred: {timeout_error}')
else:
    print(response.status_code)
    print(response.text)

In this example, we use try/except statements to catch all exceptions that may occur and take appropriate action based on the exception type.

Certificate Verification

Httpx allows you to verify SSL certificates to ensure a secure connection to your server. By default, Httpx verifies SSL certificates. If you need to disable certificate verification, you can set the verify parameter to False.

Here is an example:

import httpx

response = httpx.get('https://www.baidu.com', verify=False)
print(response.status_code)
print(response.text)

In this example, we set the verify parameter to False to disable SSL certificate verification.

Using a proxy

Httpx allows you to use a proxy to send HTTP requests. Here is an example:

import httpx

proxies = {
    'http://http-proxy-server:8080',
    'https://https-proxy-server:8080'
}

response = httpx.get('https://www.baidu.com', proxies=proxies)
print(response.status_code)
print(response.text)

In this example, we set up two proxy servers using the proxies parameter.

Upload files

Httpx allows you to upload files using the files parameter. Here is an example:

import httpx

files = {'file': ('file.txt', open('file.txt', 'rb'))}

response = httpx.post('https://www.baidu.com', files=files)
print(response.status_code)
print(response.text)

在这个示例中,我们使用 files 参数上传了名为 file.txt 的文件。

Httpx 允许您使用 cookies 参数发送 cookie。以下是一个示例:

import httpx

cookies = {'name': 'value'}

response = httpx.get('https://www.baidu.com', cookies=cookies)
print(response.status_code)
print(response.text)

在这个示例中,我们使用 cookies 参数发送了名为 name 的 cookie。

The above is the detailed content of How to use python httpx. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How do you slice a Python array?How do you slice a Python array?May 01, 2025 am 12:18 AM

The basic syntax for Python list slicing is list[start:stop:step]. 1.start is the first element index included, 2.stop is the first element index excluded, and 3.step determines the step size between elements. Slices are not only used to extract data, but also to modify and invert lists.

Under what circumstances might lists perform better than arrays?Under what circumstances might lists perform better than arrays?May 01, 2025 am 12:06 AM

Listsoutperformarraysin:1)dynamicsizingandfrequentinsertions/deletions,2)storingheterogeneousdata,and3)memoryefficiencyforsparsedata,butmayhaveslightperformancecostsincertainoperations.

How can you convert a Python array to a Python list?How can you convert a Python array to a Python list?May 01, 2025 am 12:05 AM

ToconvertaPythonarraytoalist,usethelist()constructororageneratorexpression.1)Importthearraymoduleandcreateanarray.2)Uselist(arr)or[xforxinarr]toconvertittoalist,consideringperformanceandmemoryefficiencyforlargedatasets.

What is the purpose of using arrays when lists exist in Python?What is the purpose of using arrays when lists exist in Python?May 01, 2025 am 12:04 AM

ChoosearraysoverlistsinPythonforbetterperformanceandmemoryefficiencyinspecificscenarios.1)Largenumericaldatasets:Arraysreducememoryusage.2)Performance-criticaloperations:Arraysofferspeedboostsfortaskslikeappendingorsearching.3)Typesafety:Arraysenforc

Explain how to iterate through the elements of a list and an array.Explain how to iterate through the elements of a list and an array.May 01, 2025 am 12:01 AM

In Python, you can use for loops, enumerate and list comprehensions to traverse lists; in Java, you can use traditional for loops and enhanced for loops to traverse arrays. 1. Python list traversal methods include: for loop, enumerate and list comprehension. 2. Java array traversal methods include: traditional for loop and enhanced for loop.

What is Python Switch Statement?What is Python Switch Statement?Apr 30, 2025 pm 02:08 PM

The article discusses Python's new "match" statement introduced in version 3.10, which serves as an equivalent to switch statements in other languages. It enhances code readability and offers performance benefits over traditional if-elif-el

What are Exception Groups in Python?What are Exception Groups in Python?Apr 30, 2025 pm 02:07 PM

Exception Groups in Python 3.11 allow handling multiple exceptions simultaneously, improving error management in concurrent scenarios and complex operations.

What are Function Annotations in Python?What are Function Annotations in Python?Apr 30, 2025 pm 02:06 PM

Function annotations in Python add metadata to functions for type checking, documentation, and IDE support. They enhance code readability, maintenance, and are crucial in API development, data science, and library creation.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),