python使用http.client发送post请求

import http.client
import json


def send_to_rest_api(data):
    # 设置目标URL和要发送的数据,URL为www.baidu.com/user
    host = 'www.baidu.com'
    api_url = '/user'
    # 创建HTTP连接
    conn = http.client.HTTPSConnection(host)  # 如果需要HTTPS,使用HTTPSConnection;如果是HTTP,使用HTTPConnection
    # 发送POST请求
    conn.request('POST', api_url, body=json.dumps(data), headers={'Content-Type': 'application/json'})
    # 获取响应
    response = conn.getresponse()
    # 读取响应内容
    response_data = response.read()
    # 打印响应内容
    if response.status == 200:
        api_res = json.loads(response_data.decode('utf-8'))
    else:
        # 在这里处理请求失败的情况
        print(f"Request failed with status code: {response.status}")
        conn.close()
    conn.close()

if __name__ == '__main__':
    d = {
        "a": 0.0
    }
    send_to_rest_api(d)

你可能感兴趣的:(python,开发语言,http,http.client)