java实现发送短信
时间: 2023-11-29 12:05:08 浏览: 78
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 SMSExample {
public static void main(String[] args) {
try {
// 设置短信内容
String message = "这是一条测试短信。";
// 设置接收手机号码
String phoneNumber = "手机号码";
// 设置短信签名
String signName = "短信签名";
// 设置短信模板ID
String templateId = "短信模板ID";
// 设置短信模板变量
String templateParam = "模板变量";
// 构建请求URL
String url = "http://api.example.com/sms/send?message=" + URLEncoder.encode(message, "UTF-8") +
"&phoneNumber=" + phoneNumber +
"&signName=" + URLEncoder.encode(signName, "UTF-8") +
"&templateId=" + templateId +
"&templateParam=" + URLEncoder.encode(templateParam, "UTF-8");
// 发送HTTP GET请求
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
// 获取响应结果
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 打印响应结果
System.out.println("Response Code: " + responseCode);
System.out.println("Response Body: " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
请注意,上述代码中的URL、手机号码、短信签名、短信模板ID和模板变量需要根据实际情况进行替换。
阅读全文