实现webservice发送手机验证码需要以下3步
1、webService的请求工具类
连接webservice提供的短信接口
package com.gfan.util;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.security.KeyStore;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import org.apache.log4j.Logger;
public class URLUtils {
private static Logger logger = Logger.getLogger(URLUtils.class);
public static final String METHOD_POST= "POST";
public static final String METHOD_GET = "GET";
public static final String CHARSET_ENDING_UTF8 = "UTF-8";
public static final String CHARSET_ENDING_GB2312 = "gb2312";
public static final String CHARSET_ENDING_GBK = "GBK";
/**
* HttpURLConnection
* @param url 发生请求的URL
* @param param 请求的参数
* @param method 请求的方式
* @param ConnectTimeout 连接超时时间(毫秒)
* @param ReadTimeout 读取超时时间(毫秒)
* @param outputCharsetEnding 请求数据的编码方式
* @param inputCharsetEnding 接受数据的编码方式
* @param setMsg 请求头信息,如没有则设置为null
* @return addMsg 自定义请求有信息,如没有则设置为null
* @throws IOException
* @throws UnsupportedEncodingException
* @throws UnsupportedEncodingException
*/
public static String sendURLConnection(
String url, String param,String method,int ConnectTimeout,int ReadTimeout,
String outputCharsetEnding,String inputCharsetEnding,Map<String,String> setMsg,Map<String,String> addMsg)
throws Exception {
PrintWriter printWriter = null;
BufferedReader br = null;
StringBuffer urlname = new StringBuffer(url);
if(METHOD_GET.equals(method)){
urlname.append("?").append(param);
}
URI uri = URI.create(urlname.toString());
//1.通过在 URL 上调用 openConnection 方法创建连接对象。
URL ur = new URL(uri.toASCIIString());
HttpURLConnection connection = (HttpURLConnection) ur.openConnection();
//2.处理设置参数和一般请求属性。
if(setMsg==null||setMsg.isEmpty()){
connection.setRequestProperty("Cotent-Type", "text/html");
connection.setRequestProperty("Accept-Charset", METHOD_POST);
connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
connection.setRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
connection.setRequestProperty("Cache-Control", "max-age=0");
connection.setRequestProperty("Connection", "keep-alive");
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36");
}else{
for(Map.Entry<String, String> entry : setMsg.entrySet()){
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
//3.自定义请求头
if(addMsg!=null&&!addMsg.isEmpty()){
for(Map.Entry<String, String> entry : addMsg.entrySet()){
connection.addRequestProperty(entry.getKey(), entry.getValue());
}
}
connection.setDoOutput(true);
//连接超时时间
connection.setConnectTimeout(ConnectTimeout);
//读超时时间
connection.setReadTimeout(ReadTimeout);
//设置请求方式
connection.setRequestMethod(method);
//3.使用 connect 方法建立到远程对象的实际连接。
connection.connect();
//4.远程对象变为可用。远程对象的头字段和内容变为可访问。
if(connection.getRequestMethod().equals(METHOD_POST)){
//只有当时post请求是才使用PrintWriter发送数据
printWriter = new PrintWriter(
new OutputStreamWriter(
connection.getOutputStream(), outputCharsetEnding));
//发生post数据
printWriter.print(param);
if(printWriter!=null)
printWriter.close();
}
StringBuilder result = new StringBuilder();
if(connection.getResponseCode()==200){
//无论是什么请求都会接收数据
br = new BufferedReader(
new InputStreamReader(connection.getInputStream(), inputCharsetEnding));
String line;
while((line = br.readLine())!=null){
result.append(line);
}
if(br!=null)
br.close();
}else{
logger.error("URLUtils -> sendURLConnection -> debug : {} code :" + connection.getResponseCode() + "->" + connection.getResponseMessage());
}
return result.toString().trim();
}
/**
* 获得KeyStore.
* @param keyStorePath
* 密钥库路径
* @param password
* 密码
* @return 密钥库
* @throws Exception
*/
public static KeyStore getKeyStore(String password, String keyStorePath)
throws Exception {
// 实例化密钥库
KeyStore ks = KeyStore.getInstance("PKCS12");
// 获得密钥库文件流
FileInputStream is = new FileInputStream(keyStorePath);
// 加载密钥库
ks.load(is, password.toCharArray());
// 关闭密钥库文件流
is.close();
return ks;
}
/**
* 获得SSLSocketFactory.
* @param password
* 密码
* @param keyStorePath
* 密钥库路径
* @param trustStorePath
* 信任库路径
* @return SSLSocketFactory
* @throws Exception
*/
public static SSLContext getSSLContext(String password, String keyStorePath, String trustStorePath)
throws Exception {
// 实例化密钥库
KeyManagerFactory keyManagerFactory = KeyManagerFactory
.getInstance(KeyManagerFactory.getDefaultAlgorithm());
// 获得密钥库
KeyStore keyStore = getKeyStore(password, keyStorePath);
// 初始化密钥工厂
keyManagerFactory.init(keyStore, password.toCharArray());
// 实例化信任库
TrustManagerFactory trustManagerFactory = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
// 获得信任库
KeyStore trustStore = getKeyStore(password, trustStorePath);
// 初始化信任库
trustManagerFactory.init(trustStore);
// 实例化SSL上下文
SSLContext ctx = SSLContext.getInstance("TLS");
// 初始化SSL上下文
ctx.init(keyManagerFactory.getKeyManagers(),
trustManagerFactory.getTrustManagers(), null);
// 获得SSLSocketFactory
return ctx;
}
/**
* 发送请求.
* @param httpsUrl
* 请求的地址
* @param xmlStr
* 请求的数据
*/
public static void post(String httpsUrl, String xmlStr) {
HttpsURLConnection urlCon = null;
try {
urlCon = (HttpsURLConnection) (new URL(httpsUrl)).openConnection();
urlCon.setDoInput(true);
urlCon.setDoOutput(true);
urlCon.setRequestMethod("POST");
urlCon.setRequestProperty("Content-Length",
String.valueOf(xmlStr.getBytes().length));
urlCon.setUseCaches(false);
//设置为gbk可以解决服务器接收时读取的数据中文乱码问题
urlCon.getOutputStream().write(xmlStr.getBytes("gbk"));
urlCon.getOutputStream().flush();
urlCon.getOutputStream().close();
BufferedReader in = new BufferedReader(new InputStreamReader(
urlCon.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 测试方法.
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// 密码
String password = "123456";
// 密钥库
String keyStorePath = "tomcat.keystore";
// 信任库
String trustStorePath = "tomcat.keystore";
// 本地起的https服务
String httpsUrl = "https://localhost:8443/service/httpsPost";
// 传输文本
String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><fruitShop><fruits><fruit><kind>萝卜</kind></fruit><fruit><kind>菠萝</kind></fruit></fruits></fruitShop>";
// 发起请求
URLUtils.post(httpsUrl, xmlStr);
}
}
2、解析xml工具类
解析webservice接口返回的xml结果,成功执行成功的操作,失败执行失败的操作
package com.gfan.util;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class BaseUtils {
private static Logger logger = Logger.getLogger(BaseUtils.class);
/**
* 将字符串进行base64转换
* @param value
* @return
*/
public static final String base64EncoderEncrypt(String value){
BASE64Encoder base64Encoder = new BASE64Encoder();
try {
return base64Encoder.encode(value.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
logger.error("BaseUtils->base64EncoderEncrypt error : {}" + e.getMessage());
e.printStackTrace();
return null;
}
}
/**
* 进行base64解码
* @param base64Value
* @return
*/
public static final String base64DecoderEncrypt(String base64Value){
BASE64Decoder base64Decoder = new BASE64Decoder();
try {
byte[] b = base64Decoder.decodeBuffer(base64Value);
return new String(b,"UTF-8");
} catch (IOException e) {
logger.error("BaseUtils->base64DecoderEncrypt error : {}" + e.getMessage());
e.printStackTrace();
return null;
}
}
/**
* 返回UUID随机字符串
* @return
*/
public static String UUID(){
UUID uid = UUID.randomUUID();
return uid.toString();
}
/**
* 返回UUID 根据参数生成的固定字符串
* @return
*/
public static String UUID(String param){
UUID uid = UUID.nameUUIDFromBytes(param.getBytes());
return uid.toString();
}
/**
* @explain MD5秘钥 (小写)
* @param plainText 加密参数字符
* @return
*/
public static String Md5(String plainText){
StringBuffer buf = new StringBuffer();
try {
MessageDigest md = MessageDigest.getInstance("MD5");
try {
md.update(plainText.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
byte b[] = md.digest();
int i;
for (int offset = 0; offset < b.length; offset++) {
i = b[offset];
if(i<0) i+= 256;
if(i<16) buf.append("0"); buf.append(Integer.toHexString(i));
}
}catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return buf.toString();
}
/**
* 解析XML数据。获得根节点
* @param strXml XML数据
* @return
*/
public static Element XML(String strXml){
if (StringUtils.isEmpty(strXml))
return null;
// 获得文档的根节点
Element root = null;
try {
// 将字符串转化为XML文档对象
Document document = DocumentHelper.parseText(strXml);
root = document.getRootElement();
} catch (DocumentException e) {
e.printStackTrace();
}
return root;
}
/**
* 判断用户的设备是ipad还是iphone
* @return
*/
public static String device(HttpServletRequest request){
String device = null;
String Agent = request.getHeader("User-Agent");
if(Agent.contains("iPad")){
device = "iPad";
}else if(Agent.contains("iPhone")){
device = "iPhone";
}else{
device = "iPhone";
}
return device;
}
public static void main(String[] args) {
System.out.println(BaseUtils.Md5("cH79D0pzasfse4tevgs#?afasdvczsdfawew34t45fgxcvxggyu65ewimei=862873022464504&appId=80&type=000&productId=10000&sysVer=22&versoft=android_spot_v1.0.0"));
}
}
3、手机发送短信实现
实现
/**
* @Title: UserController.java
* @Package com.gfan.api.framework.controller.action
* @Description: TODO(用一句话描述该文件做什么)
* @author chenlong
* @date 2015年9月8日 下午2:33:28
* @version V1.0
*/
package com.gfan.util;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
/**
* @ClassName VerifyCodeController
* @Description
* @author yuanjianqiang
* @date 2016年3月10日 下午3:42:49
*/
public class VerifyCodePhoneController {
private static Logger log = Logger.getLogger(VerifyCodePhoneController.class);
/**
* 手机验证码接口
*
* @return RestResponse
*/
public void mobileVerifyCode(String errorMessage) {
String mobile = GetPropertyUtil.getPropertyByName("sms", "PHONE");;
String sn = "";
String pwd = "";
String send_msg_url = "";
String result_mode = "";
String result = "";
Date now = new Date();
Map<String, Object> params = new HashMap<String, Object>();
params.put("mobile", mobile);
params.put("send_time", DateUtil.date2Str(now));
// 获取短信接口相关参数
sn = GetPropertyUtil.getPropertyByName("sms", "SN");
pwd = GetPropertyUtil.getPropertyByName("sms", "PWD");
send_msg_url = GetPropertyUtil.getPropertyByName("sms", "SEND_MSG_URL");
result_mode = GetPropertyUtil.getPropertyByName("sms", "RESULT");
// 编辑短信内容
StringBuffer sb = new StringBuffer();
sb.append("数据传输出错:");
sb.append(errorMessage);
sb.append(" 【机锋网】");
// 发送短信
// 请求头
Map<String, String> headMsg = new HashMap<String, String>();
headMsg.put("Cotent-Type", "application/x-www-form-urlencoded");
headMsg.put("Accept-Charset", URLUtils.CHARSET_ENDING_UTF8);
// 拼接发送短信参数
StringBuffer param = new StringBuffer();
param.append("sn=").append(sn);
param.append("&pwd=").append(pwd);
param.append("&mobile=").append(mobile);
param.append("&content=").append(sb.toString());
try {
result = URLUtils.sendURLConnection(send_msg_url, param.toString(),
"POST", 5000, 5000, URLUtils.CHARSET_ENDING_GBK,
URLUtils.CHARSET_ENDING_UTF8, headMsg, null);
} catch (Exception e) {
e.printStackTrace();
}
// 解析xml
result = BaseUtils.XML(result).getTextTrim();
//判断是否发送成功
if (result_mode.equals(result)) {
// 记录发送短信明细
log.info("send success,errorMessage:" + errorMessage);
System.out.println("send success");
}
}
public static void main(String[] args) {
// new VerifyCodePhoneController().mobileVerifyCode();
}
}
该工具类为通用框架所以并未实现延迟有效60S等功能,业务需要可配合使用框架实现