⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 bookmarksender.java

📁 wap短信发送
💻 JAVA
字号:
/*
 * Created on 2005-9-24
 * 
 */

/**
 * @author XenonGas Copyright http://www.04tech.com
 *  
 */
package net.mcool.www.message;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;

import javax.comm.CommPortIdentifier;
import javax.comm.PortInUseException;
import javax.comm.SerialPort;
import javax.comm.UnsupportedCommOperationException;

public class BookmarkSender {
    //端口列表
    static Enumeration portList;

    //端口标识
    static CommPortIdentifier portId;

    static SerialPort serialPort;

    //输出流
    static OutputStream outStream;

    //输入流
    static InputStream inStream;

    //等待端口响应的时间
    private int commandDelay = 50;

    //响应字符串
    private String replyString;

    //等待响应的间隔
    private int getReplyInterval;

    //错误标志
    public boolean errFlag = false;

    //端口名称
    private String portName;

    //端口波特率
    private int Baudrate = 9600;

    public static String byteArrayToHexString(byte b[]) {
        String result = "";
        for (int i = 0; i < b.length; i++)
            result = result + byteToHexString(b[i]);
        return result;
    }

    public static String byteToString(byte b[]) {
        String result = "";
        for (int i = 0; i < b.length; i++) {
            result = result + b[i];
        }
        return result;
    }

    public static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n = 256 + n;
        int d1 = n / 16;
        int d2 = n % 16;
        return HexCode[d1] + HexCode[d2];
    }

    public static String HexCode[] = { "0", "1", "2", "3", "4", "5", "6", "7",
            "8", "9", "A", "B", "C", "D", "E", "F" };

    public static String getUTFString(final String gbString) {
        if (gbString == null)
            return "";
        char[] utfBytes = gbString.toCharArray();
        String unicodeBytes = "";
        for (int byteIndex = 0; byteIndex < utfBytes.length; byteIndex++) {
            String hexB = "";
            if (utfBytes[byteIndex] < '!') {
                hexB = Integer.toHexString(utfBytes[byteIndex]);
                if (hexB.length() <= 2) {
                    hexB = "00" + hexB;
                }
                unicodeBytes = unicodeBytes + "&#x" + hexB + ";";
            } else {
                unicodeBytes += utfBytes[byteIndex];
            }
        }
        return unicodeBytes;
    }

    //*****************************************************************
    //不断读取返回信号,当收到OK信号时,停止读取,以执行下面的操作
    public void getReply() {
        while (this.replyString != null) {
            if (this.replyString.equals("OK")
                    || this.replyString.equals("ERROR"))
                return;
            waitForRead(this.getReplyInterval);
        }
    }

    //*****************************************************************
    //监听端口
    public void listenSerialPort() {
        if (this.errFlag == true)
            return;
        if (BookmarkSender.serialPort == null) {
            returnStateInfo("不存在" + this.portName + ",请检查相关配置!");
            this.errFlag = true;
            return;
        }
        //设置输入输出流
        try {
            outStream = (OutputStream) BookmarkSender.serialPort
                    .getOutputStream();
            inStream = (InputStream) BookmarkSender.serialPort.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            //监听端口
            BookmarkSender.serialPort.notifyOnDataAvailable(true);
            BookmarkSender.serialPort.notifyOnBreakInterrupt(true);
        } catch (Exception e) {
            BookmarkSender.serialPort.close();
            returnStateInfo(e.getMessage());
        }
        try {
            BookmarkSender.serialPort.enableReceiveTimeout(20);
        } catch (UnsupportedCommOperationException e) {
            e.printStackTrace();
        }
        //设置端口的基本参数
        try {
            BookmarkSender.serialPort.setSerialPortParams(this.Baudrate,
                    SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);
        } catch (UnsupportedCommOperationException e) {
            e.printStackTrace();
        }
    } //********************************************************************

    //********************************************************************
    //对串口的读写操作
    public void writeToSerialPort(String msgString) {
        try {
            BookmarkSender.outStream.write(msgString.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void waitForRead(int waitTime) {
        try {
            Thread.sleep(waitTime);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //********************************************************************
    //发送消息
    public boolean sendmsg(String messageString, String phoneNumber, String URL)
            throws Exception {
        byte[] readBuffer = new byte[1];
        int msglength, msgurllength;

        //开始监听端口
        listenSerialPort();

        //等待OK信号
        getReply();

        //选择短信格式
        writeToSerialPort("AT+CMGF=0\r");

        //等待一段时间再写
        waitForRead(this.commandDelay);
        //System.out.println("Send CMGF");
        try {
            inStream = serialPort.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        try {
            while (inStream.available() > 0) {
                int numBytes = inStream.read(readBuffer);
                //System.out.print(new String(readBuffer));
            }
            //System.out.println("\n");
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        //System.out.println("CMGF OK");

        String sendmessage, tempSendString;
        //消息长度
        msglength = (messageString).length();
        msgurllength = URL.length();

        //发送短信息
        String atcmgs = "AT+CMGS= ";

        //System.out.println("URL and CONTENT");
        //System.out.println(byteArrayToHexString(URL.getBytes()));
        //System.out.println(byteArrayToHexString(messageString.getBytes("UTF-8")));
        //System.out.println("URL and CONTENT OK");

        //URL转换成十六进制字符串
        String hexURL = byteArrayToHexString(URL.getBytes());
        //内容转换成十六进制字符串
        String hexMessage = byteArrayToHexString(messageString
                .getBytes("UTF-8"));
        String content = "0B0504C34FC002000304010101062D1F2A6170706C69636174696F6E2F782D7761702D70726F762E62726F777365722D626F6F6B6D61726B730081EA01016A0045C67F0187151103"
                + hexMessage + "000187171103" + hexURL + "00010101";
        tempSendString = "00F5A7"
                + Integer.toHexString((content.length() / 2)).toUpperCase()
                + content;

        if (phoneNumber.trim().length() > 0) {
            sendmessage = "0051000D91" + changePhoneNumber(phoneNumber)
                    + tempSendString;
            //pdu串总长度
            int pduLength = (sendmessage.length() / 2 - 1);
            //如果总长度过长,失败
            if (pduLength > 154) {
                System.out.println("总长度过长!");
                return false;
            }

            atcmgs += (sendmessage.length() / 2 - 1);
            writeToSerialPort(atcmgs + "\r");
            waitForRead(this.commandDelay);

            //System.out.println("Send CMGS");

            try {
                inStream = serialPort.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }

            try {
                while (inStream.available() > 0) {
                    int numBytes = inStream.read(readBuffer);
                    //System.out.print(new String(readBuffer));
                }
                //System.out.println("\n");

            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }

            //System.out.println("CMGS OK");

            writeToSerialPort(sendmessage + (char) 26);
            //13488692297
            //3184682992F7
            waitForRead(this.commandDelay);
            //System.out.println("SEND PDU");
            try {
                inStream = serialPort.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }

            try {
                while (inStream.available() > 0) {
                    int numBytes = inStream.read(readBuffer);
                    //waitForRead(this.commandDelay);
                    //System.out.print(new String(readBuffer));
                }
                //System.out.println("\n");

            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }

            //System.out.println("PDU OK");

            //System.out.println(sendmessage);

            waitForRead(this.commandDelay);

            try {
                outStream.write((char) 26);
            } catch (IOException ioe) {
                ioe.printStackTrace();
                return false;
            }
            getReply();

            if (this.replyString == null) {
                return true;
            } else if (this.replyString.equals("OK")) {
                return true;
            } else if (this.replyString.equals("ERROR")) {
                return false;
            }
        }

        return true;
    }

    //*****************************************************************
    public String changePhoneNumber(String phoneNumber) {
        phoneNumber = "86" + phoneNumber;
        int numberLength = phoneNumber.length();
        if (phoneNumber.length() % 2 != 0) {
            phoneNumber = phoneNumber + "F";
            numberLength += 1;
        }
        char newPhoneNumber[] = new char[numberLength];
        for (int i = 0; i < numberLength; i += 2) {
            newPhoneNumber[i] = phoneNumber.charAt(i + 1);
            newPhoneNumber[i + 1] = phoneNumber.charAt(i);
        }
        return (new String(newPhoneNumber));
    }

    //*****************************************************************

    //*****************************************************************
    //转换为UNICODE编码
    public String asc2unicode(StringBuffer msgString) {
        StringBuffer msgReturn = new StringBuffer();
        int msgLength = msgString.length();
        if (msgLength > 0) {
            for (int i = 0; i < msgLength; i++) {
                new Integer((int) msgString.charAt(0)).toString();
                msgReturn.append(new StringBuffer());
                String msgCheck = new String(Integer
                        .toHexString((int) msgString.charAt(i)));
                if (msgCheck.length() < 4) {
                    msgCheck = "00" + msgCheck;
                }
                msgReturn.append(new StringBuffer(msgCheck));
            }
        }
        return (new String(msgReturn).toUpperCase());
    }

    //*****************************************************************
    private void returnStateInfo(String errInfo) {
        System.out.println(errInfo);
    }

    public boolean sendBookmark(String messageString, String phoneNumber,
            String URL) {
        boolean result = false;
        portList = CommPortIdentifier.getPortIdentifiers();
        BookmarkSender pduw = new BookmarkSender();
        while (portList.hasMoreElements()) {
            portId = (CommPortIdentifier) portList.nextElement();
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                if (portId.getName().equals("COM1")) {
                    try {
                        serialPort = (SerialPort) portId.open("SimpleWriteApp",
                                2000);
                    } catch (PortInUseException e) {
                        e.printStackTrace();
                        return false;
                    }

                    try {
                        outStream = serialPort.getOutputStream();
                        inStream = serialPort.getInputStream();
                    } catch (IOException e) {
                        e.printStackTrace();
                        return false;
                    }

                    try {
                        serialPort.setSerialPortParams(9600,
                                SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
                                SerialPort.PARITY_NONE);
                    } catch (UnsupportedCommOperationException e) {
                        e.printStackTrace();
                        return false;
                    }

                    try {
                        result = pduw.sendmsg(messageString, phoneNumber, URL);
                        serialPort.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                        return false;
                    }
                }
            }
        }

        return result;
    }

    public static void main(String[] args) {
        BookmarkSender pw = new BookmarkSender();
        if (pw.sendBookmark("乐酷免费Wap!", "13521262171",
                "http://wap.joycool.net")) {
            System.out.println("成功发送!");
        } else {
            System.out.println("失败");
        }
    }

    //	public static void main(String[] args){
    //		if(args == null){
    //			return;
    //		} else if(args.length != 3){
    //			return;
    //		} else {
    //			PDUWrite pw = new PDUWrite();
    //			pw.sendWapPush(args[1], args[0], args[2]);
    //		}
    //	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -