1. pom.xml 引入依赖:
<dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.1</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.1</version> </dependency> |
2. 创建一个 util 包 ,存放 SendMsg_webchinese.java 工具类:
import java.io.*; import java.util.Random; import org.apache.commons.httpclient.*; import org.apache.commons.httpclient.methods.PostMethod; public class SendMsg_webchinese { public SendMsg_webchinese() { } public static String Yan() { String str = "0123456789"; StringBuilder sb = new StringBuilder(4); for (int i = 0; i < 4; i++) { char ch = str.charAt((new Random()).nextInt(str.length())); sb.append(ch); } String zheng = sb.toString(); return zheng; } public static void LY(String iphone, String zheng) { HttpClient client = new HttpClient(); PostMethod post = new PostMethod("http://utf8.api.smschinese.cn/"); post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); NameValuePair data[] = { new NameValuePair("Uid", "lylony"), new NameValuePair("Key", "1b1dd221aee7962efb0c"), new NameValuePair("smsMob", iphone), new NameValuePair("smsText", (new StringBuilder("验证码:")).append(zheng).append("(小试牛刀)").toString()) }; post.setRequestBody(data); try { client.executeMethod(post); } catch (IOException e) { e.printStackTrace(); } Header headers[] = post.getResponseHeaders(); int statusCode = post.getStatusCode(); System.out.println((new StringBuilder("statusCode:")).append(statusCode).toString()); Header aheader[]; int j = (aheader = headers).length; for (int i = 0; i < j; i++) { Header h = aheader[i]; System.out.println(h.toString()); } String result = null; try { result = new String(post.getResponseBodyAsString().getBytes("gbk")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println(result); post.releaseConnection(); } |
3. 创建 test.java 进行测试:
import java.util.Scanner; public class test { public static void main(String[] args) { SendMsg_webchinese sendMsg_webchinese = new SendMsg_webchinese(); String yan = SendMsg_webchinese.Yan(); SendMsg_webchinese.LY("13838381438", yan); Scanner sc = new Scanner(System.in); System.out.println("请输入验证码"); String string = sc.next(); if(string.equals(yan)){ System.out.println("成功"); }else{ System.out.println("失败"); } } |
4. 运行main方法,稍微等一会儿,手机短信就来了。