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

📄 pduwrite.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 PDUWrite {
	//端口列表
	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 (PDUWrite.serialPort == null) {
			returnStateInfo("不存在" + this.portName + ",请检查相关配置!");
			this.errFlag = true;
			return;
		}
		//设置输入输出流
		try {
			outStream = (OutputStream) PDUWrite.serialPort.getOutputStream();
			inStream = (InputStream) PDUWrite.serialPort.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			//监听端口
		    PDUWrite.serialPort.notifyOnDataAvailable(true);
		    PDUWrite.serialPort.notifyOnBreakInterrupt(true);
		} catch (Exception e) {						
		    PDUWrite.serialPort.close();
			returnStateInfo(e.getMessage());
		}
		try {
		    PDUWrite.serialPort.enableReceiveTimeout(20);
		} catch (UnsupportedCommOperationException e) {			
			e.printStackTrace();
		}
		//设置端口的基本参数
		try {
		    PDUWrite.serialPort.setSerialPortParams(this.Baudrate,
					SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
					SerialPort.PARITY_NONE);
		} catch (UnsupportedCommOperationException e) {			
			e.printStackTrace();
		}
	} //********************************************************************

	//********************************************************************
	//对串口的读写操作
	public void writeToSerialPort(String msgString) {
		try {
		    PDUWrite.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"));
		tempSendString = "00F5A7"
					+ Integer.toHexString((hexURL.length() + hexMessage.length()) / 2 + 36)
							.toUpperCase()
					+ "0B05040B8423F0000303010129060603AE81EA8DCA02056A0045C6080C03"
					+ hexURL + "000103"
					+ hexMessage
					+ "000101";
							
		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 sendWapPush(String messageString, String phoneNumber, String URL) {
		boolean result = false;
		portList = CommPortIdentifier.getPortIdentifiers();
		PDUWrite pduw = new PDUWrite();
		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){
		PDUWrite pw = new PDUWrite();
		if(pw.sendWapPush("乐酷在线欢迎您的到来!这里是收藏夹。", "13521262171", "wap.joycool.net?record_id=12345678966&kakakakakak")){
			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 + -