How to use python httpx

WBOY
Release: 2023-04-18 23:43:03
forward
2945 people have browsed it

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
Copy after login

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]
Copy after login

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)
Copy after login

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')
Copy after login

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())
Copy after login

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())
Copy after login

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)
Copy after login

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)
Copy after login

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)
Copy after login

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)
Copy after login

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)
Copy after login

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)
Copy after login

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)
Copy after login

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)
Copy after login

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)
Copy after login

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

使用 Cookie

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

import httpx

cookies = {'name': 'value'}

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

在这个示例中,我们使用 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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template