java写一个发送短信的工具类
时间: 2024-05-15 17:16:10 浏览: 110
SMSUtils.java短信发送工具类
下面是一个简单的Java发送短信的工具类:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class SMSUtil {
private static final String SMS_URL = "http://sms.com/sendSMS.php";
private static final String SMS_USERNAME = "your_username";
private static final String SMS_PASSWORD = "your_password";
public static void sendSMS(String phoneNumber, String message) throws Exception {
// Encode phone number and message
String encodedPhoneNumber = URLEncoder.encode(phoneNumber, "UTF-8");
String encodedMessage = URLEncoder.encode(message, "UTF-8");
// Create the SMS URL
String smsUrl = SMS_URL + "?username=" + SMS_USERNAME + "&password=" + SMS_PASSWORD + "&phone=" + encodedPhoneNumber + "&message=" + encodedMessage;
// Send the SMS
URL url = new URL(smsUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
// Read the response
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String response = reader.readLine();
reader.close();
// Check the response
if (!response.startsWith("OK")) {
throw new Exception("Failed to send SMS: " + response);
}
}
}
```
使用方式:
```java
try {
SMSUtil.sendSMS("1234567890", "Hello, World!");
System.out.println("SMS sent successfully");
} catch (Exception e) {
System.err.println("Error sending SMS: " + e.getMessage());
}
```
注意:这个工具类是一个简单的示例,实际使用时需要替换SMS_URL、SMS_USERNAME和SMS_PASSWORD为你自己的信息。另外,这个工具类只支持GET方式发送短信,实际使用时可能需要根据短信服务商的要求修改为POST方式。
阅读全文