dululu / GitNote

0 stars 0 forks source link

urllib3 #38

Open dululu opened 6 months ago

dululu commented 6 months ago

urllib3是一个Python的第三方库,用于在HTTP请求中处理连接池、编码、重试等功能。它提供了一个高级的HTTP客户端接口,简化了与Web服务器进行通信的过程。

HEAD请求和GET请求在HTTP协议中是两种不同的请求方法,


更灵活地处理请求和响应。

data = { 'name': 'John Doe', 'age': 30 } encoded_data = json.dumps(data).encode('utf-8')

response = http.request('POST', 'http://www.example.com', body=encoded_data, headers={'Content-Type': 'application/json'})

在上面的示例中,我们将数据编码为`JSON`格式并将其作为body参数传递给`POST`请求方法。还设置了请求头部中的`Content-Type为application/json`,指示服务器接收`JSON`格式的数据。
- **处理响应**:`urllib3`的响应对象提供了许多属性和方法来处理响应数据。例如,可以使用`response.status`获取响应的状态码,`response.headers`获取响应头部信息,`response.data`获取响应的内容等。
```python
response = http.request('GET', 'http://www.example.com')
status_code = response.status
headers = response.headers
data = response.data
dululu commented 6 months ago

JSON格式

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,常用于在不同应用程序之间传输和存储结构化数据。它基于JavaScript语法,但已成为一种独立于编程语言的通用数据格式。 以下是JSON的一些特点和常见用法:

  • 数据结构:JSON数据由键值对组成,类似于字典或映射的结构。键是字符串可以是字符串、数字、布尔值、数组、嵌套的JSON对象或null。
    {
    "name": "John",
    "age": 30,
    "isStudent": false,
    "scores": [95, 85, 90],
    "address": {
    "street": "123 Main St",
    "city": "New York"
    },
    "contact": null
    }
  • 大多数编程语言中,都提供了用于解析和生成JSON的库和函数。这些工具可以将JSON数据解析为对应的数据结构(如字典、列表)或对象,并将数据结构转换为JSON格式的字符串。
    
    import json

解析JSON字符串

json_str = '{"name": "John", "age": 30}' data = json.loads(json_str) print(data["name"]) # 输出: John

生成JSON字符串

data = {"name": "John", "age": 30} json_str = json.dumps(data) print(json_str) # 输出: {"name": "John", "age": 30}