如何使用Python通过API发送短信?附请求示例
Hey there! Sending SMS through this XML-based API with Python is totally straightforward, and since you already have the request structure mapped out, let's turn that into working code step by step.
First off, we'll use Python's requests library—it's the go-to tool for making HTTP requests without unnecessary hassle. If you don't have it installed yet, run this quick command in your terminal:
pip install requests
Next, here's the full code example that uses your provided XML request structure. Just remember to replace the placeholder values with your actual service details:
import requests # Build your XML payload using the structure you provided xml_payload = """<?xml version="1.0" encoding="UTF-8"?> <request> <head> <operation>submit</operation> <login>user</login> <!-- Swap with your real login credentials --> <password>pass</password> <!-- Replace with your actual password --> <title>title</title> <isbulk>false</isbulk> <scheduled>2018-04-04 17:55:05</scheduled> <!-- Adjust or remove if you don't need scheduling --> <controlid>188</controlid> </head> <body> <msisdn>676775</msisdn> <!-- Replace with the target phone number --> <message>test from code</message> <!-- Update with your actual SMS content --> </body> </request>""" # Replace this with your SMS API's official endpoint URL api_endpoint = "https://your-sms-provider-api.com/submit" try: # Send the POST request with the XML payload response = requests.post( api_endpoint, data=xml_payload, headers={"Content-Type": "application/xml"} ) # Ensure the request was successful response.raise_for_status() # Print the API response to confirm submission print("SMS request sent successfully!") print("API Response:", response.text) except requests.exceptions.RequestException as e: # Catch and display any errors that pop up print(f"Oops, something went wrong: {e}")
Quick Tips to Avoid Issues:
- Update Placeholders: Don't forget to swap out
user,pass,api_endpoint,msisdn, andmessagewith your real credentials and target details. - Content-Type Header: Setting
Content-Type: application/xmltells the API exactly what kind of data we're sending—skip this and your request might get rejected. - Scheduled Time: If you don't need to delay sending the SMS, check your provider's docs to see if you can omit the
<scheduled>tag entirely. - Error Handling: The
try-exceptblock catches common problems like network drops or invalid API responses, making it easier to debug if things go sideways.
That's all there is to it! This code should handle sending your SMS via the XML API smoothly. If you hit specific errors (like authentication fails or invalid XML), double-check your credentials and the XML structure against your provider's documentation.
内容的提问来源于stack exchange,提问作者TheNone

