发送短信肯定需要使用第三方接口,Java本身是肯定不能直接发送短信的。第三方接口有很多,这里直接找个正规靠谱一点的学习一下
这里使用了中国网建(http://www.smschinese.cn/)
①打开网址后,点击立刻注册体验
②登陆后,点击【修改短信密钥】,查看当前密钥:
③点击【短信API接口】,查看示例代码
Jar包依赖:
<dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.1</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.4</version> </dependency> |
示例代码:
import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod;
public class SendMsg_webchinese {
public static void main(String[] args) throws Exception {
HttpClient client = new HttpClient(); PostMethod post = new PostMethod("http://gbk.api.smschinese.cn"); post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=gbk");// 在头文件中设置转码 NameValuePair[] data = { new NameValuePair("Uid", "***"), // 注册的用户名 new NameValuePair("Key", "***"), // 短信密钥 new NameValuePair("smsMob", "***"), // 接收短信的手机 new NameValuePair("smsText", "验证码:8888") };// 要发送的短信内容 post.setRequestBody(data);
client.executeMethod(post); Header[] headers = post.getResponseHeaders(); int statusCode = post.getStatusCode(); System.out.println("statusCode:" + statusCode); for (Header h : headers) { System.out.println(h.toString()); } String result = new String(post.getResponseBodyAsString().getBytes("gbk")); System.out.println(result); // 打印返回消息状态
post.releaseConnection(); } } |
运行程序,手机即可收到信息。