or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

authentication.mdcaching.mderror-handling.mdhttp-client.mdindex.mdproxy-support.mdresponse-handling.mdutilities.md

http-client.mddocs/

0

# HTTP Client

1

2

Core HTTP client functionality providing request/response handling, connection management, caching, and authentication. The Http class serves as the primary interface for all HTTP operations in httplib2.

3

4

## Capabilities

5

6

### Http Class

7

8

The main HTTP client class that manages connections, handles caching, authentication, redirects, and compression. Supports both HTTP and HTTPS with extensive configuration options.

9

10

```python { .api }

11

class Http:

12

def __init__(self, cache=None, timeout=None, proxy_info=None,

13

ca_certs=None, disable_ssl_certificate_validation=False,

14

tls_maximum_version=None, tls_minimum_version=None):

15

"""

16

Initialize HTTP client.

17

18

Args:

19

cache: Cache object or directory path for caching

20

timeout (float): Socket timeout in seconds

21

proxy_info: ProxyInfo object or function returning ProxyInfo

22

ca_certs (str): Path to CA certificates file

23

disable_ssl_certificate_validation (bool): Skip SSL cert validation

24

tls_maximum_version: Maximum TLS version

25

tls_minimum_version: Minimum TLS version

26

"""

27

28

def request(self, uri, method="GET", body=None, headers=None,

29

redirections=5, connection_type=None):

30

"""

31

Perform a single HTTP request.

32

33

Args:

34

uri (str): Absolute URI of the HTTP resource

35

method (str): HTTP method (GET, POST, PUT, DELETE, etc.)

36

body (str or bytes): Entity body to send with request

37

headers (dict): Extra headers to send with request

38

redirections (int): Maximum number of redirects to follow (default 5)

39

connection_type: Connection class to use

40

41

Returns:

42

tuple: (Response, content) where Response contains status/headers

43

and content is the response body as bytes

44

45

Raises:

46

HttpLib2Error: Base class for all httplib2 errors

47

RedirectLimit: Too many redirects

48

ServerNotFoundError: Server hostname not found

49

RelativeURIError: URI is relative when absolute required

50

"""

51

52

def add_credentials(self, name, password, domain=""):

53

"""

54

Add credentials for authentication.

55

56

Args:

57

name (str): Username

58

password (str): Password

59

domain (str): Authentication domain (optional)

60

"""

61

62

def add_certificate(self, key, cert, domain, password=None):

63

"""

64

Add client certificate for authentication.

65

66

Args:

67

key (str): Path to private key file

68

cert (str): Path to certificate file

69

domain (str): Domain for certificate usage

70

password (str): Private key password (optional)

71

"""

72

73

def clear_credentials(self):

74

"""Remove all stored authentication credentials."""

75

76

def close(self):

77

"""

78

Close persistent connections and clear sensitive data.

79

Not thread-safe, requires external synchronization.

80

"""

81

```

82

83

### Usage Examples

84

85

#### Basic GET Request

86

87

```python

88

import httplib2

89

90

h = httplib2.Http()

91

(resp, content) = h.request("http://example.org/")

92

print(f"Status: {resp.status}")

93

print(f"Content-Type: {resp['content-type']}")

94

print(f"Body: {content.decode('utf-8')}")

95

```

96

97

#### POST Request with Body and Headers

98

99

```python

100

import httplib2

101

102

h = httplib2.Http()

103

body = '{"key": "value"}'

104

headers = {

105

'content-type': 'application/json',

106

'user-agent': 'MyApp/1.0'

107

}

108

109

(resp, content) = h.request(

110

"https://api.example.com/data",

111

"POST",

112

body=body,

113

headers=headers

114

)

115

```

116

117

#### Request with Authentication

118

119

```python

120

import httplib2

121

122

h = httplib2.Http()

123

h.add_credentials('username', 'password', 'api.example.com')

124

125

(resp, content) = h.request("https://api.example.com/protected")

126

```

127

128

#### Request with Caching

129

130

```python

131

import httplib2

132

133

# Use file-based cache in .cache directory

134

h = httplib2.Http(".cache")

135

136

# First request - fetches from server and caches

137

(resp, content) = h.request("http://example.org/")

138

139

# Second request - may use cached version if valid

140

(resp, content) = h.request("http://example.org/")

141

142

# Force fresh request ignoring cache

143

headers = {'cache-control': 'no-cache'}

144

(resp, content) = h.request("http://example.org/", headers=headers)

145

```

146

147

#### Request with Custom SSL Configuration

148

149

```python

150

import httplib2

151

152

h = httplib2.Http(

153

ca_certs="/path/to/cacerts.pem",

154

disable_ssl_certificate_validation=False,

155

tls_minimum_version="TLSv1_2"

156

)

157

158

(resp, content) = h.request("https://secure.example.com/")

159

```

160

161

#### Request with Proxy

162

163

```python

164

import httplib2

165

166

proxy_info = httplib2.ProxyInfo(

167

httplib2.socks.PROXY_TYPE_HTTP,

168

'proxy.example.com',

169

8080,

170

proxy_user='proxyuser',

171

proxy_pass='proxypass'

172

)

173

174

h = httplib2.Http(proxy_info=proxy_info)

175

(resp, content) = h.request("http://example.org/")

176

```

177

178

### Connection Management

179

180

httplib2 automatically manages HTTP connections:

181

182

- **Keep-Alive**: Reuses connections when possible for better performance

183

- **Connection Pool**: Maintains pool of connections per hostname

184

- **Timeout Handling**: Configurable socket timeouts

185

- **SSL/TLS**: Full HTTPS support with certificate validation

186

- **Proxy Support**: HTTP, HTTPS, and SOCKS proxy support

187

188

### HTTP Methods

189

190

All HTTP methods are supported:

191

192

- **GET**: Retrieve data from server

193

- **POST**: Send data to server

194

- **PUT**: Update resource on server

195

- **DELETE**: Remove resource from server

196

- **HEAD**: Get headers only (no body)

197

- **PATCH**: Partial resource update

198

- **OPTIONS**: Get allowed methods

199

- **TRACE**: Echo request for debugging

200

201

### Content Handling

202

203

- **Automatic Decompression**: Handles gzip and deflate compression

204

- **Content-Type**: Preserves original content-type headers

205

- **Encoding**: Returns content as bytes, preserving original encoding

206

- **Chunked Transfer**: Supports chunked transfer encoding

207

- **Content-Length**: Handles both fixed-length and streaming content

208

209

### Redirect Handling

210

211

- **Automatic Redirects**: Follows 3XX redirects for GET requests

212

- **Redirect Limits**: Configurable maximum redirect count (default 5)

213

- **Status Codes**: Handles 300, 301, 302, 303, 307, 308 redirects

214

- **Location Header**: Validates and follows Location header values

215

- **Permanent Redirects**: Caches 301 redirects to avoid future requests