Java實現(xiàn)短信自動發(fā)送功能主要是用httpclient實現(xiàn)的,要有發(fā)短信的端口。
在龍崗等地區(qū),都構(gòu)建了全面的區(qū)域性戰(zhàn)略布局,加強發(fā)展的系統(tǒng)性、市場前瞻性、產(chǎn)品創(chuàng)新能力,以專注、極致的服務(wù)理念,為客戶提供成都網(wǎng)站設(shè)計、網(wǎng)站制作 網(wǎng)站設(shè)計制作按需設(shè)計,公司網(wǎng)站建設(shè),企業(yè)網(wǎng)站建設(shè),品牌網(wǎng)站建設(shè),營銷型網(wǎng)站,外貿(mào)網(wǎng)站制作,龍崗網(wǎng)站建設(shè)費用合理。
1、硬件設(shè)備是一個3G網(wǎng)卡;
2、軟件方面需要sun提過的java底層通信common包;
3、此外還需要第三方庫SMSLib,這個是開源項目,主要用于實現(xiàn)java發(fā)短信的功能;
主要代碼如下:
HttpClient?client?=?new?HttpClient();
PostMethod?post?=?new?PostMethod(
"");
post.addRequestHeader("Content-Type",
"application/x-www-form-urlencoded;charset=utf-8");//?在頭文件中設(shè)置轉(zhuǎn)碼
NameValuePair[]?data?=?{?new?NameValuePair("sname",?"*****"),
new?NameValuePair("spwd",?"*****"),
new?NameValuePair("scorpid",?"*****"),
new?NameValuePair("sprdid",?"*****"),
new?NameValuePair("sdst",?"*****"),
new?NameValuePair("smsg",?"*****")?};
post.setRequestBody(data);
client.executeMethod(post);
Header[]?headers?=?post.getResponseHeaders();
int?statusCode?=?post.getStatusCode();
System.out.println("statusCode:"?+?statusCode);
for?(Header?h?:?headers)?{
System.out.println(h.toString());
}
String?result?=?new?String(post.getResponseBodyAsString().getBytes("utf-8"));
System.out.println(result);
post.releaseConnection();
Java源程序(.java文件)——java字節(jié)碼文件(.class文件)——由解釋執(zhí)行器(java.exe)將字節(jié)碼文件加載到j(luò)ava虛擬機(jvm)——字節(jié)碼文件(.class)就會在java虛擬機中執(zhí)行。
Java是一門面向?qū)ο缶幊陶Z言,不僅吸收了C++語言的各種優(yōu)點,還摒棄了C++里難以理解的多繼承、指針等概念,因此Java語言具有功能強大和簡單易用兩個特征。Java語言作為靜態(tài)面向?qū)ο缶幊陶Z言的代表,極好地實現(xiàn)了面向?qū)ο罄碚?,允許程序員以優(yōu)雅的思維方式進行復(fù)雜的編程? ?。
Java具有簡單性、面向?qū)ο蟆⒎植际?、健壯性、安全性、平臺獨立與可移植性、多線程、動態(tài)性等特點? 。Java可以編寫桌面應(yīng)用程序、Web應(yīng)用程序、分布式系統(tǒng)和嵌入式系統(tǒng)應(yīng)用程序等
那你要做的就是向這個URL發(fā)送數(shù)據(jù)就好,給個例子:
public???class??Httptest1??{
8??
9???????public???static???void??main(String[]?args)??{
10??
11?????????URL?url??=???null?;
12?????????HttpURLConnection?conn??=???null?;
13?????????OutputStream?outStream??=???null?;
14?????????InputStream?inStream??=???null?;
15?????????
16???????????try???{
17?????????????url??=???new??URL(?"??"?);
18?????????????conn??=??(HttpURLConnection)?url.openConnection();
19?????????????conn.setDoOutput(?true?);
20?????????????conn.setDoInput(?true?);
21??
22?????????????String?sendXml??=???"??xml?version=\?"?1.0?\?"??encoding=\?"?UTF?-?16?\?"??!DOCTYPE?SigMailCommand?SYSTEM?\?"?SigMail.dtd\?"?"?;??//?XML數(shù)據(jù)?????
23??????????????sendXml??+=???"?SigMailCommand?Name=\?"?checkuser\?"?Param?Name=\?"?domainname\?"?test.com.cn/Param?"?;
24?????????????sendXml??+=???"?Param?Name=\?"?username\?"?admin/Param/SigMailCommand?"?;
25??
26?????????????outStream??=??conn.getOutputStream();
27??
28??????????????//?準備通過CONN對象寫入XML數(shù)據(jù)?
29??????????????BufferedWriter?bw??=???new??BufferedWriter(?new??java.io.OutputStreamWriter(outStream,
30??????????????"?UTF-16?"?));
31?????????????bw.write(sendXml);
32?????????????bw.flush();
33?????????????bw.close();
34?????????????
35??????????????//?DataOutputStream?dataOutStream?=?new?DataOutputStream(outStream);
36??????????????//?dataOutStream.writeChars(xml);
37??????????????//?dataOutStream.flush();
38??????????????//?dataOutStream.close();
39?????????????
40??
41??????????????//?準備通過CONN對象讀取返回的XML數(shù)據(jù)?
42??
43?????????????inStream??=??conn.getInputStream();
44?????????????StringBuffer?returnXml??=???new??StringBuffer(?""?);
45?????????????BufferedReader?rd??=???new??BufferedReader(?new??InputStreamReader(inStream,
46??????????????????????"?UTF-16?"?));
47???????????????for??(String?line??=???null?;?(line??=??rd.readLine())??!=???null?;)??{
48?????????????????returnXml.append(line);
49?????????????}?
50?????????????System.out.println(returnXml.toString());
51?????????????rd.close();
52??????????}???catch??(IOException?ex)??{
53?????????????ex.printStackTrace();
54??????????}?finally?{
55???????????????try???{
56??????????????????if??(outStream??!=???null?)
57?????????????????????outStream.close();
58??????????????????if??(inStream??!=???null?)
59?????????????????????inStream.close();
60??????????????????if??(conn??!=???null?)
61?????????????????????conn.disconnect();
62??????????????}???catch??(IOException?e)??{
63??????????????????//??TODO?自動生成?catch?塊?
64??????????????????e.printStackTrace();
65?????????????}?
66?????????}?
67??
68?????}?
69??
70?}
這段代碼本身只是利用java訪問了一個url:(",后面帶了一堆的參數(shù):String data = "user_id=" + user_id + "password=" + password +
"mobile_phone=" + mobile_phone +
"msg=" + URLEncoder.encode(msg, "GBK") + "send_date=" + send_date +
"subcode=" + subcode;
,僅此而已,至于具體要怎么發(fā),那就要看這個URL提供放的后臺是如何定義參數(shù)的含義了。
1.通過移動或聯(lián)通短信網(wǎng)關(guān)發(fā)送短信,這需要通信服務(wù)商給你開通短信端口,發(fā)送短信協(xié)議各個服務(wù)商都不一樣,比如移動的是cmpp2,cmpp3等
2.第二種是通過硬件設(shè)備發(fā)送短信,這個需要你有專門的硬件設(shè)備,比如一個上網(wǎng)卡或者一個手機模塊,通過調(diào)用com遵從一些協(xié)議發(fā)送短信
單純靠寫代碼是無法發(fā)短信的,至少要有一個WEBSERVICE接口或者硬件接口。
package examples;
import java.util.Scanner;
public class Entry {
public static void main(String args []) {
Scanner sc=new Scanner(System.in);
String pno,msg;
System.out.print("請輸入短信內(nèi)容:");
msg=sc.nextLine();
System.out.println("請輸入目標手機號碼:");
pno=sc.nextLine();
ShortMesg newmsg=new ShortMesg();
newmsg.setPhoneNO(pno);
newmsg.setMessage(msg);
SendMesg send=new SendMesg(newmsg);
send.send();
}
}
class ShortMesg {
public ShortMesg() {
}
private String pno,msg;
public void setPhoneNO(String pno) {
this.pno=pno;
}
public String getPhoneNO() {
return this.pno;
}
public void setMessage( String msg) {
this.msg=msg;
}
public String getMessage() {
return this.msg;
}
}
class SendMesg {
private ShortMesg mms;
public SendMesg(ShortMesg mms) {
this.mms=mms;
}
public void send() {
System.out.println("短信內(nèi)容: "+mms.getMessage());
System.out.println("目標手機: "+mms.getPhoneNO()+"\n");
}
}
package?com.winhands.quartz;
import?java.io.PrintWriter;
import?java.io.StringWriter;
import?java.io.UnsupportedEncodingException;
import?java.util.ArrayList;
import?java.util.Date;
import?java.util.HashMap;
import?java.util.List;
import?org.slf4j.Logger;
import?org.slf4j.LoggerFactory;
import?com.winhands.base.service.BaseService;
import?com.winhands.util.BaseConstant;
import?com.winhands.web.dict.entity.DictCommon;
import?com.winhands.web.xfhf.entity.SmsOutBox;
import?com.winhands.web.xfhf.entity.SmsVisit;
import?com.winhands.web.xfhf.entity.TaskInfo;
public?class?SmsSendSync?{
public?BaseService?baseService;
public?BaseService?baseServiceMas;
public?static?final?Logger?logger?=?LoggerFactory.getLogger(SmsSendSync.class);
//同步短信到mas機待發(fā)短信表
public?void?work()?{
//?任務(wù)ID?100001
//?首先查詢?nèi)蝿?wù)是否正在執(zhí)行
//?查詢列表
TaskInfo?taskInfo?=?new?TaskInfo();
taskInfo.setTask_id("100001");
try?{
taskInfo?=?(TaskInfo)?baseService.queryForObject("sms_send.queryTaskStatus",?taskInfo);
//如果狀態(tài)是處室狀態(tài)則執(zhí)行,否則此次任務(wù)不執(zhí)行
if?(BaseConstant.task_status_cs.equals(taskInfo.getTask_status()))?{
taskInfo.setTask_status(BaseConstant.task_status_zx);//設(shè)置任務(wù)執(zhí)行狀態(tài)為執(zhí)行
taskInfo.setTask_last_start_time(new?Date());//設(shè)置任務(wù)執(zhí)行開始時間
baseService.update("sms_send.updateTaskStatus",?taskInfo);//
//移動號碼庫
HashMapString,String?hashMap?=?new?HashMapString,String();
//134?、135、136、137、138、139、150、151、152、158、159、182、183、184。157、187、188
hashMap.put("134",?"134");
hashMap.put("135",?"135");
hashMap.put("136",?"136");
hashMap.put("137",?"137");
hashMap.put("138",?"138");
hashMap.put("139",?"139");
hashMap.put("150",?"150");
hashMap.put("151",?"151");
hashMap.put("152",?"152");
hashMap.put("157",?"157");
hashMap.put("158",?"158");
hashMap.put("159",?"159");
hashMap.put("182",?"182");
hashMap.put("183",?"183");
hashMap.put("184",?"184");
hashMap.put("187",?"187");
hashMap.put("188",?"188");
SmsVisit?smsSend?=?new?SmsVisit();
smsSend.setSms_status(BaseConstant.sms_status_csh);
List?list?=?baseService.queryForList("sms_send.queryForSmsTask",?smsSend);
List?smsMasList?=?new?ArrayList();
List?smsList?=?new?ArrayList();
if?(list?==?null||list.size()==0)?return;//?如果列表為空,沒有待辦任務(wù),則任務(wù)結(jié)束
for?(int?i?=?0;?i??list.size();?i++)?{
smsSend?=?(SmsVisit)?list.get(i);
//String?msg?=?messagecontent(smsSend);
String?msg?=?smsSend.getSpare_2();
if(hashMap.get(smsSend.getVisit_phone().substring(0,?3))!=null){
SmsOutBox?smsOutBox?=?new?SmsOutBox();
smsOutBox.setSismsid(smsSend.getP_id());
smsOutBox.setReqdeliveryreport(BaseConstant.NoReport);
smsOutBox.setApplicationid(BaseConstant.APPLICATIONID);
smsOutBox.setDestaddr(smsSend.getVisit_phone());
smsOutBox.setMsgfmt(BaseConstant.MSGFMT);
smsOutBox.setRequesttime(new?Date());
smsOutBox.setExtcode(smsSend.getExtccode());
smsOutBox.setSendmethod(BaseConstant.NoMsg);//?正常短信
smsOutBox.setMessagecontent(msg);
smsMasList.add(smsOutBox);
}else{
boolean?con?=?true;
String?lastMsg?=?msg;
int?xh?=0;
while(con){
lastMsg?=?msg.substring(0,msg.length()??55???55?:?msg.length());
msg?=?msg.substring(msg.length()??55???55?:?msg.length(),msg.length());
if?(msg.equals(""))?{
con?=?false;
}
SmsOutBox?smsOutBox?=?new?SmsOutBox();
smsOutBox.setSismsid(smsSend.getP_id()+(xh==0?"":xh));
xh++;
smsOutBox.setReqdeliveryreport(BaseConstant.NoReport);
smsOutBox.setApplicationid(BaseConstant.APPLICATIONID);
smsOutBox.setDestaddr(smsSend.getVisit_phone());
smsOutBox.setMsgfmt(BaseConstant.MSGFMT);
smsOutBox.setRequesttime(new?Date());
smsOutBox.setExtcode(smsSend.getExtccode());
smsOutBox.setSendmethod(BaseConstant.NoMsg);//?正常短信
smsOutBox.setMessagecontent(lastMsg);
smsMasList.add(smsOutBox);
}
}
SmsVisit?smsSendTemp?=?new?SmsVisit();
smsSendTemp.setP_id(smsSend.getP_id());?
//smsSendTemp.setSpare_2(msg);//短信內(nèi)容
smsSendTemp.setSms_status_time(new?Date());
smsSendTemp.setSms_status(BaseConstant.sms_status_yfswg);?
smsList.add(smsSendTemp);
}
baseService.insertBatch("sms_send.insertSmsOutBox",?smsMasList);//插入本地歷史記錄表
baseServiceMas.insertBatch("sms_mas.insertSmsOutBox",?smsMasList);//插入mas機待發(fā)送表
baseService.updateBatch("sms_send.updateSmsVisit",?smsList);//更新回訪記錄狀態(tài)
}
}?catch?(Exception?e)?{
e.printStackTrace();
//baseService.saveLog("同步短信到mas機待發(fā)短信表",?"100001",?"同步短信到mas機待發(fā)短信表錯誤");
logger.error("同步短信到mas機待發(fā)短信表錯誤",?getTrace(e));
}finally{
try?{
taskInfo.setTask_status(BaseConstant.task_status_cs);//設(shè)置任務(wù)執(zhí)行狀態(tài)為初始
taskInfo.setTask_last_end_time(new?Date());//設(shè)置任務(wù)執(zhí)行結(jié)束時間
taskInfo.setTask_status_desc("任務(wù)執(zhí)行結(jié)束");
baseService.update("sms_send.updateTaskStatus",?taskInfo);//
}?catch?(Exception?e2)?{
e2.printStackTrace();
//?TODO:?handle?exception
}
}
}
public?String?messagecontent(SmsVisit?smsSend){
//XX,您好!您于XX月XX日辦理XX業(yè)務(wù)(或XX,您好!XX大隊于XX月XX日對你單位進行監(jiān)督檢查/行政處罰/火災(zāi)調(diào)查),現(xiàn)進行滿意度回訪,請回復(fù)數(shù)字:1為滿意;2為基本滿意;3為不滿意。感謝您對消防工作的支持!回復(fù)免費。宿遷市公安消防支隊
//首先根據(jù)業(yè)務(wù)類型來判斷采用哪種模板?監(jiān)察
StringBuffer?msg?=?new?StringBuffer("");?
if(BaseConstant.jiancha.equals(smsSend.getVisit_deal_business_type())){
msg.append(smsSend.getVisit_name_cn())
???.append(",您好!")
???.append(smsSend.getVisit_deal_org_name())
???.append("于")
???.append(smsSend.getVisit_deal_time().substring(4,?6)).append("月")
???.append(smsSend.getVisit_deal_time().substring(6,?8)).append("日")
???.append("對你單位進行").append(DictCommon.getEntryMap(BaseConstant.jiancha).get(smsSend.getVisit_deal_business()))
???.append(",現(xiàn)進行滿意度回訪,請回復(fù)數(shù)字:1為滿意;2為基本滿意;3為不滿意。感謝您對消防工作的支持!");
}else?if(BaseConstant.yewu.equals(smsSend.getVisit_deal_business_type())){
msg.append(smsSend.getVisit_name_cn())
???.append(",您好!您于")
???.append(smsSend.getVisit_deal_time().substring(4,?6)).append("月")
???.append(smsSend.getVisit_deal_time().substring(6,?8)).append("日")
???.append("辦理").append(smsSend.getVisit_deal_business()).append("業(yè)務(wù),")
???.append("現(xiàn)進行滿意度回訪,請回復(fù)數(shù)字:1為滿意;2為基本滿意;3為不滿意。感謝您對消防工作的支持!");
}
return?msg.toString();
}
public?BaseService?getBaseService()?{
return?baseService;
}
public?void?setBaseService(BaseService?baseService)?{
this.baseService?=?baseService;
}
public?BaseService?getBaseServiceMas()?{
return?baseServiceMas;
}
public?void?setBaseServiceMas(BaseService?baseServiceMas)?{
this.baseServiceMas?=?baseServiceMas;
}
public?static?void?main(String[]?args){
List?smsMasList?=?new?ArrayList();?
try?{
String?msg?=?"***,您好!*********于2015年5月2日對你單位進行監(jiān)督檢查,現(xiàn)進行滿意度回訪,請回復(fù)數(shù)字:1為滿意;2為基本滿意;3為不滿意。感謝您對消防工作的支持!";
SmsOutBox?smsOutBox?=?new?SmsOutBox();
smsOutBox.setSismsid("12344");
smsOutBox.setReqdeliveryreport(BaseConstant.NoReport);
smsOutBox.setApplicationid(BaseConstant.APPLICATIONID);
smsOutBox.setDestaddr("111");
smsOutBox.setMsgfmt(BaseConstant.MSGFMT);
smsOutBox.setRequesttime(new?Date());
smsOutBox.setExtcode("2222");
smsOutBox.setSendmethod(BaseConstant.NoMsg);//?正常短信
boolean?con?=?true;
String?lastMsg?=?msg;
while(con){
lastMsg?=?msg.substring(0,msg.length()??55???55?:?msg.length());
msg?=?msg.substring(msg.length()??55???55?:?msg.length(),msg.length());
if?(msg.equals(""))?{
con?=?false;
}
SmsOutBox?smOutBox_temp?=?new?SmsOutBox();?
smOutBox_temp?=?smsOutBox;
smOutBox_temp.setMessagecontent(lastMsg);
?
smsMasList.add(smOutBox_temp);
}
for(Object?o:smsMasList){
SmsOutBox?smsOutBox2?=?(SmsOutBox)o;
System.out.println(smsOutBox2.getMessagecontent());
}
}?catch?(Exception?e)?{
//?TODO?Auto-generated?catch?block
e.printStackTrace();
}
}
public?static?String?getTrace(Throwable?t)?{
StringWriter?stringWriter=?new?StringWriter();
PrintWriter?writer=?new?PrintWriter(stringWriter);
t.printStackTrace(writer);
StringBuffer?buffer=?stringWriter.getBuffer();
return?buffer.toString();
}
}
短信不是你想發(fā)??想發(fā)就能發(fā),是收費的,我們公司是租用的移動MAS平臺的短信發(fā)送接收平臺,上面那是和一個和mas同步的一個小程序,租用別人的mas平臺是收費的,平臺有很多自己選擇,有發(fā)送接口可以調(diào),發(fā)送內(nèi)容自己提供