配置文件:
sendUrl : http://ems.smsway.com.cn/sendSMS.action
代码:
import java.net.MalformedURLException; import java.net.URL; import java.util.Map; import org.apache.log4j.Logger; import org.apache.struts2.ServletActionContext; import com.common.common.ProPertiesUtil; import com.duogou.mall.service.common.StringUtil; import com.ems.util.HttpUtil; import com.ems.util.MD5; import com.ems.util.XmlUtil; public class SmsUtil { private static Logger logger = Logger.getLogger(SmsUtil.class); public static Boolean sendSms(String mobile,String content) { boolean nFlag = false; String sendURL = ProPertiesUtil.getValue("/sms.properties", "sendURL"); //企业id String enterpriseID = ProPertiesUtil.getValue("/sms.properties", "enterpriseID"); //登录名 String loginName = ProPertiesUtil.getValue("/sms.properties", "loginName"); //密码 String password = ProPertiesUtil.getValue("/sms.properties", "password"); //消息id String smsId = ""; //扩展端口 String subPort = ""; //定时发送时间 String sendTime = ""; //post内容 String postContent = ""; //返回结果 String returnXML = ""; try { postContent = "enterpriseID=" + enterpriseID + "&loginName=" + loginName + "&password=" + MD5.toMD5(password) + "&smsId=" + smsId + "&subPort=" + subPort + "&content=" + java.net.URLEncoder.encode(content, "UTF-8") + "&mobiles=" + mobile + "&sendTime=" +sendTime; returnXML = HttpUtil.httpPostRequest(new URL(sendURL), postContent); } catch (Exception e) { // TODO Auto-generated catch block logger.error(e.getStackTrace()); return false; } // System.out.println("sendURL returnXML = " + returnXML); //解释xml结果 Map map = null; map = XmlUtil.getNodeValues(XmlUtil.getRootElement(returnXML)); String result = (String)map.get("Result"); //应用时判断,若该值为0表示成功往下取smsid,若不为0则是相应错误代码。 System.out.println(result); if(result.equals("0")){ //发送成功 String SmsId = (String)map.get("SmsId"); System.out.println(SmsId); if(StringUtil.isNotEmpty(SmsId)){ nFlag = true; // System.out.println("发送成功"); // System.out.println("result = " + result + " SmsId = " + SmsId); } }else{ // System.out.println("发送失败"); } return nFlag; } public static void main(String[] args) throws MalformedURLException, Exception { SmsUtil.sendSms("139999999", "验证码:123123"); } }
工具类:
发送请求:HttpUtil.httpPostRequest
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.URL; import java.net.URLConnection; import java.util.Map; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.log4j.Logger; public class HttpUtil { private static final Logger logger = Logger.getLogger(HttpUtil.class); /** * http post请求 * @param url 地址 * @param postContent post内容格式为param1=value¶m2=value2¶m3=value3 * @return * @throws IOException */ public static String httpPostRequest(URL url, String postContent) throws Exception{ OutputStream outputstream = null; BufferedReader in = null; try { URLConnection httpurlconnection = url.openConnection(); httpurlconnection.setConnectTimeout(10 * 1000); httpurlconnection.setDoOutput(true); httpurlconnection.setUseCaches(false); OutputStreamWriter out = new OutputStreamWriter(httpurlconnection .getOutputStream(), "UTF-8"); out.write(postContent); out.flush(); StringBuffer result = new StringBuffer(); in = new BufferedReader(new InputStreamReader(httpurlconnection .getInputStream(),"UTF-8")); String line; while ((line = in.readLine()) != null) { result.append(line); } return result.toString(); } catch(Exception ex){ logger.error("post请求异常:" + ex.getMessage()); throw new Exception("post请求异常:" + ex.getMessage()); } finally { if (outputstream != null) { try { outputstream.close(); } catch (IOException e) { outputstream = null; } } if (in != null) { try { in.close(); } catch (IOException e) { in = null; } } } } /** * 通过httpClient进行post提交 * @param url 提交url地址 * @param charset 字符集 * @param keys 参数名 * @param values 参数值 * @return * @throws Exception */ public static String HttpClientPost(String url , String charset , String[] keys , String[] values) throws Exception{ HttpClient client = null; PostMethod post = null; String result = ""; int status = 200; try { client = new HttpClient(); //PostMethod对象用于存放地址 //总账户的测试方法 post = new PostMethod(url); //NameValuePair数组对象用于传入参数 post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=" + charset);//在头文件中设置转码 String key = ""; String value = ""; NameValuePair temp = null; NameValuePair[] params = new NameValuePair[keys.length]; for (int i = 0; i < keys.length; i++) { key = (String)keys[i]; value = (String)values[i]; temp = new NameValuePair(key , value); params[i] = temp; temp = null; } post.setRequestBody(params); //执行的状态 status = client.executeMethod(post); logger.info("status = " + status); if(status == 200){ result = post.getResponseBodyAsString(); } } catch (Exception ex) { // TODO: handle exception throw new Exception("通过httpClient进行post提交异常:" + ex.getMessage() + " status = " + status); } finally{ post.releaseConnection(); } return result; } /** * 字符串处理,如果输入字符串为null则返回"",否则返回本字符串去前后空格。 * @param inputStr 输入字符串 * @return string 输出字符串 */ public static String doString(String inputStr){ //如果为null返回"" if(inputStr == null || "".equals(inputStr) || "null".equals(inputStr)){ return ""; } //否则返回本字符串把前后空格去掉 return inputStr.trim(); } /** * 对象处理,如果输入对象为null返回"",否则则返回本字符对象信息,去掉前后空格 * @param object * @return */ public static String doString(Object object){ //如果为null返回"" if(object == null || "null".equals(object) || "".equals(object)){ return ""; } //否则返回本字符串把前后空格去掉 return object.toString().trim(); } }
解析XML:
XmlUtil.getNodeValues
import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; public class XmlUtil { private static final Logger logger = Logger.getLogger(XmlUtil.class); /** * 获得根据节点信息 * @param xml xml字符串 * @return */ public static Element getRootElement(String xml){ Document doc = null; Element root = null; try { doc = DocumentHelper.parseText(xml); root = doc.getRootElement(); } catch (Exception ex) { // TODO: handle exception logger.error("解释xml文件出现异常:" + ex.getMessage()); } return root; } /** * 获得指定元素下所有节点属性及值 * @param element * @return */ public static Map getNodeValues(Element element){ Element root = null; Map map = new HashMap(); try { List list = element.elements(); Element e = null; for (int i = 0; i < list.size(); i++) { e = (Element)list.get(i); map.put(e.getName(), e.getText()); } } catch (Exception ex) { // TODO: handle exception logger.error("获得指定元素下所有节点属性及值出现异常: " + ex.getMessage()); } return map; } /** * 获得指定节点指定属性值 * @param element 元素名称 * @param attributeName 属性名称 * @return */ public static String getElementAttributeValue(Element element,String attributeName){ String value = ""; try { value = element.attributeValue("attributeName"); } catch (Exception ex) { // TODO: handle exception logger.error("获得指定节点指定属性值出现异常: " + ex.getMessage()); } return value; } public static void main(String[] args) { try { String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Response><Result>0</Result><Mo num=\"2\"><Item id=\"1\" content=\"上行01\" from_mobile=\"13500000000\" to_port=\"0001\" rec_time=\"2013-07-20 13:23:45\"/><Item id=\"2\" content=\"上行02\" from_mobile=\"13600000000\" to_port=\"0002\" rec_time=\"2013-07-20 13:23:45\"/></Mo></Response >"; Map map = XmlUtil.getNodeValues(XmlUtil.getRootElement(xml)); String result = (String)map.get("Result"); System.out.println("result = " + result ); Element mo = XmlUtil.getRootElement(xml).element("Mo"); System.out.println("mo = " + mo); int num = Integer.parseInt(mo.attributeValue("num")); System.out.println("size = " + num); Element item = null; List list = mo.elements(); for (int i = 0; i < list.size(); i++) { item = (Element)list.get(i); System.out.println("id = " + item.attributeValue("id") + " content = " + item.attributeValue("content") + " from_mobile = " + item.attributeValue("from_mobile") + " to_port = " + item.attributeValue("to_port") + " rec_time = " + item.attributeValue("rec_time")); } } catch (Exception e) { // TODO: handle exception System.out.println("ERROR:" + e.getMessage()); } } }
扫描二维码关注公众号,回复:
710784 查看本文章