java 调用运营商短信方法(一)
一、编写短信服务器端代码:
package com.enjoy.base.common.util;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
public class SmsClient {
protected String smsSvcUrl = "************"; //服务器URL 地址
protected String cust_code = "*******"; //账号
protected String password = "******"; //密码
protected String sp_code = "**********"; //接入码(扩展码)
public void sendSms(String mobiles, String content) throws IOException {
sendSms(mobiles, content, sp_code, 0);
}
public void sendSms(String mobiles, String content, long task_id)
throws IOException {
sendSms(mobiles, content, sp_code, task_id);
}
public void sendSms(String mobiles, String content, String sp_code)
throws IOException {
sendSms(mobiles, content, sp_code, 0);
}
public void sendSms(String mobiles, String content, String sp_code,
long task_id) throws IOException {
String urlencContent = URLEncoder.encode(content,"utf-8");
//String sign = MD5.getMD5((urlencContent + password).getBytes());
// String sign=MD5.sign(urlencContent, password, "utf-8");
String sign = MD5NewUtil.sign(urlencContent+password);
System.out.println(sign);
String mobiles_utf8 = URLEncoder.encode(mobiles, "UTF-8");
String postData = "content=" + urlencContent + "&destMobiles="
+ mobiles_utf8 + "&sign=" + sign + "&cust_code=" + cust_code
+ "&sp_code=" + sp_code + "&task_id=" + task_id;
System.err.println(postData);
URL myurl = new URL(smsSvcUrl);
URLConnection urlc = myurl.openConnection();
urlc.setReadTimeout(1000 * 30);
urlc.setDoOutput(true);
urlc.setDoInput(true);
urlc.setAllowUserInteraction(false);
DataOutputStream server = new DataOutputStream(urlc.getOutputStream());
//System.out.println("发送数据=" + postData);
server.write(postData.getBytes("utf-8"));
server.close();
BufferedReader in = new BufferedReader(new InputStreamReader(
urlc.getInputStream(), "utf-8"));
String resXml = "", s = "";
while ((s = in.readLine()) != null)
resXml = resXml + s + "\r\n";
in.close();
System.out.println("接收数据=" + URLDecoder.decode(resXml,"utf-8"));
}
public static void main(String[] args) {
SmsClient client = new SmsClient();
try {
client.sendSms("手机号", "【公司名称】短信内容。");
} catch (IOException e) {
e.printStackTrace();
}
}
}
二、在服务层方法调用
for(Object obj : userlist){
Object[] objarry = (Object[]) obj;
String userName=(String) objarry[0];
String mobile=(String) objarry[1];
String url = sbCodeUtils.getCodeDefMapNV("SYS_URL").get("URL_JDC_PUSH_BJ_P");
url+="?userName="+userName+"&msg="+Hex64EncodeUtils.stringToUnicode(content);
System.out.println(url);
//发送短信
try {
UrlUtils.getConnectionStr(url, "utf-8", 10000);
if(!StringUtil.isEmpty(mobile)){
SmsClient client = new SmsClient();
client.sendSms(mobile, "您有一条来自"+useradmin.getNickname()+"的报警信息,请及时处理。");
}
} catch (IOException e) {
e.printStackTrace();
}
}
三、测试短信