发短信功能

来源:互联网 发布:ipad迷你能开淘宝店吗 编辑:程序博客网 时间:2024/04/28 10:36

package com.kuuwin.util.sms;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import org.apache.log4j.Logger;

/**
 * 短信发送接口,内部通过服务商发送短信
 * @author zdx
 */
public class SMS {
 private static Logger log = Logger.getLogger(SMS.class);
 
 private static String url = "http://sms.chinapoo.com/";
 private static String userName = "aaa";
 private static String password = "123456";
 private static String lx = "4";
 private static String no = "金蛋商城";
 /**
  * 发送短信
  * @param mobile
  * @param content 内容,不能超过50个汉字
  * @return
  */
 public static boolean sendSMS(String mobile, String content) {
  if(content == null || "".equals(content)) {
   return false;
  }
  if(mobile == null || "".equals(mobile)) {
   return false;
  }
  
  String dstUrl = url;
  dstUrl = dstUrl + "?un=" + userName + "&pw=" + password + "&no=" + no + "&lx=4";
  
  String c = content;
  try {
   c = URLEncoder.encode(content, "GBK");
  } catch (UnsupportedEncodingException e) {
  }
  
  dstUrl = dstUrl + "&mb=" + mobile + "&msg=" + c;
  
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  try {
   sendGet(dstUrl, out);
  } catch (Exception e) {
   log.error("send sms error", e);
   return false;
  }
  try {
   String result = new String(out.toByteArray(), "GBK");
   if("发送失败".equals(result.trim())) {
    return false;
   } else {
    return true;
   }
  } catch (Exception e) {
   //gbk肯定支持,不可能跑出异常
   e.printStackTrace();
   return false;
  }
 }
 
    /**
     * 发送http get请求,请求结果写入resultOut流中,如果失败,抛出异常
     * @param resultOut
     * @param content
     * @throws Exception
     */
    private static void sendGet(String urlString, OutputStream resultOut) throws Exception {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        //conn.setDoOutput(true);
        conn.setRequestMethod("GET");
       
        //int code = conn.getResponseCode();
       
        InputStream in = conn.getInputStream();
        byte[] buffer = new byte[1024];
        for(;;) {
            int n = in.read(buffer);
            if(n<0) {
             break;
            }
            resultOut.write(buffer, 0, n);
            if(n<1024) {
                //break;
            }
        }
        in.close();
        conn.disconnect();
    }
 
 public static void main(String[] argc) {
  System.out.println(SMS.sendSMS("186000000000", "测试短信"));
 }
}

原创粉丝点击