以下是一个示例代码,演示如何通过API从本地主机发送请求到网络主机:
import requests
def send_request(url, payload):
try:
response = requests.post(url, json=payload)
if response.status_code == 200:
return response.json()
else:
return {"error": f"Request failed with status code {response.status_code}"}
except requests.exceptions.RequestException as e:
return {"error": str(e)}
# 示例用法
url = "http://api.example.com"
payload = {"data": "example"}
result = send_request(url, payload)
print(result)
在这个示例中,我们使用了Python的requests
库来发送HTTP请求。send_request
函数接受一个URL和有效负载(在这个示例中是一个JSON对象),并发送一个POST请求到指定的URL。如果请求成功,它将返回响应的JSON数据。如果请求失败(如网络错误或无效的URL),它将返回一个包含错误信息的JSON对象。
你可以根据你的实际需求来修改和扩展这个示例代码。注意,你可能需要安装requests
库,可以使用pip install requests
命令来安装它。