Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Making HTTP Requests with Python's httpx Library

Tech 1

Setting Custom Headers

import httpx

headers = {
    'User-Agent': 'CustomAgent/1.0 (Platform; SystemInfo)'
}
response = httpx.get('https://httpbin.org/get', headers=headers)

print(response.text)

Enabling HTTP/2 Protocol

By default, httpx uses HTTP/1.1. To enable HTTP/2:

import httpx
client = httpx.Client(http2=True)

response = client.get('https://example.org/')
print(response.text)

Cleint Object Usage

The Client object in httpx is similar to Session in requests:

import httpx

with httpx.Client() as client:
    response = client.get('https://httpbin.org/get')
    print(response)

Alternative syntax:

client = httpx.Client()
try:
    response = client.get('https://httpbin.org/get')
finally:
    client.close()

Configuring Client Parameters

url = 'http://httpbin.org/headers'
headers = {'User-Agent': 'CustomApp/1.0'}

with httpx.Client(headers=headers) as client:
    r = client.get(url)
    print(r.json()['headers']['User-Agent'])

HTTP/2 with Client

import httpx
client = httpx.Client(http2=True)

response = client.get('https://httpbin.org/get')
print(response.text)
print(response.http_version)

AsyncClient for Asynchronous Requests

httpx also supports asynchronous requests through AsyncClient.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.