首先需要去平台注册账号以及秘钥
这里以中国网建为例 官网:http://sms.webchinese.com.cn
代码如下:
package com.yetech; 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 MailController { public static void main(String[] args) throws Exception{ HttpClient client = new HttpClient(); PostMethod post = new PostMethod("http://utf8.api.smschinese.cn/"); //这里以 Utf-8编码Url 为例 post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf8");//在头文件中设置转码 NameValuePair[] data ={ new NameValuePair("Uid", "ch152********"),//用户名 new NameValuePair("Key", "d41d8cd98f00b204e980"),//秘钥 new NameValuePair("smsMob","158********,183********"),//接收人手机号 多个以逗号隔开 new NameValuePair("smsText","验证码:" + (int)((Math.random()*9+1)*100000))};//随机生成6位验证码 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("utf8")); System.out.println(result); //打印返回消息状态 post.releaseConnection();//http请求后,关闭流 } }
需要引入的jar包依赖:
<dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.3</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>