【发布时间】:2011-02-03 22:51:39
【问题描述】:
从 Java 应用程序发送和接收短信的可能方式有哪些?
怎么做?
【问题讨论】:
从 Java 应用程序发送和接收短信的可能方式有哪些?
怎么做?
【问题讨论】:
有Ogham 库。发送 SMS 的代码很容易编写(它会自动处理字符编码和消息拆分)。真正的 SMS 使用 SMPP 协议(标准 SMS 协议)或通过提供商发送。 您甚至可以使用 SMPP 服务器在本地测试您的代码,以在支付真正的 SMS 发送费用之前检查您的 SMS 的结果。
package fr.sii.ogham.sample.standard.sms;
import java.util.Properties;
import fr.sii.ogham.core.builder.MessagingBuilder;
import fr.sii.ogham.core.exception.MessagingException;
import fr.sii.ogham.core.service.MessagingService;
import fr.sii.ogham.sms.message.Sms;
public class BasicSample {
public static void main(String[] args) throws MessagingException {
// [PREPARATION] Just do it once at startup of your application
// configure properties (could be stored in a properties file or defined
// in System properties)
Properties properties = new Properties();
properties.setProperty("ogham.sms.smpp.host", "<your server host>"); // <1>
properties.setProperty("ogham.sms.smpp.port", "<your server port>"); // <2>
properties.setProperty("ogham.sms.smpp.system-id", "<your server system ID>"); // <3>
properties.setProperty("ogham.sms.smpp.password", "<your server password>"); // <4>
properties.setProperty("ogham.sms.from.default-value", "<phone number to display for the sender>"); // <5>
// Instantiate the messaging service using default behavior and
// provided properties
MessagingService service = MessagingBuilder.standard() // <6>
.environment()
.properties(properties) // <7>
.and()
.build(); // <8>
// [/PREPARATION]
// [SEND A SMS]
// send the sms using fluent API
service.send(new Sms() // <9>
.message().string("sms content")
.to("+33752962193"));
// [/SEND A SMS]
}
}
还有很多其他features和samples/spring samples。
【讨论】:
有一个叫做 SMSLib 的 API,它真的很棒。 http://smslib.org/
现在您有很多 Saas 提供商可以使用他们的 API 为您提供这项服务
例如:mailchimp、esendex、Twilio、...
【讨论】:
您可以为此使用Twilio。但是,如果您正在寻找一些棘手的解决方法,您可以按照我在下面提到的解决方法。
这对于接收短信是不可能的。但这是一种棘手的方法,您可以使用它向多个客户端发送短信。您可以使用推特 API。我们可以通过手机短信关注 twitter 帐户。我们只需要发送短信到 Twitter。假设我们创建了一个用户名为@username 的推特账户。然后我们可以发送短信到40404,如下图。
follow @username
然后我们开始获取在该帐户中发布的推文。
因此,在我们创建一个 Twitter 帐户之后,我们就可以使用 Twitter API 从该帐户发布推文。然后,正如我之前提到的,所有关注该帐户的客户都开始接收推文。
您可以通过以下链接了解如何使用 twitter API 发布推文。
在开始开发之前,您必须获得使用 twitter api 的许可。您可以从以下链接访问 twitter api。
这不是解决您问题的最佳解决方案。但希望对您有所帮助。
【讨论】:
您可以将 Nexmo 用于send SMS 以及receive SMS。
使用Nexmo Java Library 发送短信相当简单。在creating a new account 之后,租用一个虚拟号码,并获取您的 API 密钥和秘密,您可以使用该库发送短信,如下所示:
public class SendSMS {
public static void main(String[] args) throws Exception {
AuthMethod auth = new TokenAuthMethod(API_KEY, API_SECRET);
NexmoClient client = new NexmoClient(auth);
TextMessage message = new TextMessage(FROM_NUMBER, TO_NUMBER, "Hello from Nexmo!");
//There may be more than one response if the SMS sent is more than 160 characters.
SmsSubmissionResult[] responses = client.getSmsClient().submitMessage(message);
for (SmsSubmissionResult response : responses) {
System.out.println(response);
}
}
}
要接收 SMS,您需要设置一个使用 webhook 的服务器。这也很简单。我建议在receiving SMS with Java 上查看我们的教程。
披露:我为 Nexmo 工作
【讨论】:
我们也喜欢Wavecell 中的 Java,但是这个问题可以在没有特定语言细节的情况下回答,因为我们有一个 REST API 可以满足您的大部分需求:
curl -X "POST" https://api.wavecell.com/sms/v1/amazing_hq/single \
-u amazing:1234512345 \
-H "Content-Type: application/json" \
-d $'{ "source": "AmazingDev", "destination": "+6512345678", "text": "Hello, World!" }'
如果您在使用 Java 发送 HTTP 请求时遇到问题,请查看以下问题:
【讨论】:
您可以使用 AT&T 命令通过 GSM 调制解调器发送短信。
【讨论】:
(免责声明:我在 Twilio 工作)
Twilio offers a Java SDK 用于通过 Twilio REST API 发送 SMS。
【讨论】:
我建议使用基于云的解决方案,例如 Twilio。基于云的解决方案比内部解决方案更具成本效益,因为不需要持续维护。通过电子邮件发送短信并不是一个优雅的解决方案,因为您必须从用户那里获取运营商信息,而且您永远无法确定您可以向所有手机号码发送短信。 我在我的 Web 应用程序中使用 twilio java api,从服务器端发送短信。几分钟内,您就可以与您的应用集成。
https://www.twilio.com/docs/java/install
以下是从文档发送 SMS 消息的示例:
import com.twilio.sdk.TwilioRestClient;
import com.twilio.sdk.TwilioRestException;
import com.twilio.sdk.resource.factory.MessageFactory;
import com.twilio.sdk.resource.instance.Message;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.util.ArrayList;
import java.util.List;
public class Example {
// Find your Account Sid and Token at twilio.com/user/account
public static final String ACCOUNT_SID = "{{ account_sid }}";
public static final String AUTH_TOKEN = "{{ auth_token }}";
public static void main(String[] args) throws TwilioRestException {
TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
// Build a filter for the MessageList
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Body", "Test Twilio message"));
params.add(new BasicNameValuePair("To", "+14159352345"));
params.add(new BasicNameValuePair("From", "+14158141829"));
MessageFactory messageFactory = client.getAccount().getMessageFactory();
Message message = messageFactory.create(params);
System.out.println(message.getSid());
}
}
【讨论】:
首先你需要设置Java Comm Api
This Article Describes In Detail How to Set Up Communication Api
接下来你需要一个 GSM 调制解调器(最好是 sim900 模块)
最好是Java JDK最新版本
AT 命令指南
包装样本;
import java.io.*;
import java.util.*;
import gnu.io.*;
import java.io.*;
import org.apache.log4j.chainsaw.Main;
import sun.audio.*;
public class GSMConnect implements SerialPortEventListener,
CommPortOwnershipListener {
private static String comPort = "COM6"; // This COM Port must be connect with GSM Modem or your mobile phone
private String messageString = "";
private CommPortIdentifier portId = null;
private Enumeration portList;
private InputStream inputStream = null;
private OutputStream outputStream = null;
private SerialPort serialPort;
String readBufferTrial = "";
/** Creates a new instance of GSMConnect */
public GSMConnect(String comm) {
this.comPort = comm;
}
public boolean init() {
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals(comPort)) {
System.out.println("Got PortName");
return true;
}
}
}
return false;
}
public void checkStatus() {
send("AT+CREG?\r\n");
}
public void send(String cmd) {
try {
outputStream.write(cmd.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMessage(String phoneNumber, String message) {
char quotes ='"';
send("AT+CMGS="+quotes + phoneNumber +quotes+ "\r\n");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// send("AT+CMGS=\""+ phoneNumber +"\"\r\n");
send(message + '\032');
System.out.println("Message Sent");
}
public void hangup() {
send("ATH\r\n");
}
public void connect() throws NullPointerException {
if (portId != null) {
try {
portId.addPortOwnershipListener(this);
serialPort = (SerialPort) portId.open("MobileGateWay", 2000);
serialPort.setSerialPortParams(115200,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
} catch (PortInUseException | UnsupportedCommOperationException e) {
e.printStackTrace();
}
try {
inputStream = serialPort.getInputStream();
outputStream = serialPort.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
/** These are the events we want to know about*/
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
serialPort.notifyOnRingIndicator(true);
} catch (TooManyListenersException e) {
e.printStackTrace();
}
//Register to home network of sim card
send("ATZ\r\n");
} else {
throw new NullPointerException("COM Port not found!!");
}
}
public void serialEvent(SerialPortEvent serialPortEvent) {
switch (serialPortEvent.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[2048];
try {
while (inputStream.available() > 0)
{
int numBytes = inputStream.read(readBuffer);
System.out.print(numBytes);
if((readBuffer.toString()).contains("RING")){
System.out.println("Enter Inside if RING Loop");
}
}
System.out.print(new String(readBuffer));
} catch (IOException e) {
}
break;
}
}
public void outCommand(){
System.out.print(readBufferTrial);
}
public void ownershipChange(int type) {
switch (type) {
case CommPortOwnershipListener.PORT_UNOWNED:
System.out.println(portId.getName() + ": PORT_UNOWNED");
break;
case CommPortOwnershipListener.PORT_OWNED:
System.out.println(portId.getName() + ": PORT_OWNED");
break;
case CommPortOwnershipListener.PORT_OWNERSHIP_REQUESTED:
System.out.println(portId.getName() + ": PORT_INUSED");
break;
}
}
public void closePort(){
serialPort.close();
}
public static void main(String args[]) {
GSMConnect gsm = new GSMConnect(comPort);
if (gsm.init()) {
try {
System.out.println("Initialization Success");
gsm.connect();
Thread.sleep(5000);
gsm.checkStatus();
Thread.sleep(5000);
gsm.sendMessage("+91XXXXXXXX", "Trial Success");
Thread.sleep(1000);
gsm.hangup();
Thread.sleep(1000);
gsm.closePort();
gsm.outCommand();
System.exit(1);
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("Can't init this card");
}
}
}
【讨论】:
【讨论】:
这取决于您的工作方式以及您的提供者是谁。
如果您与 sms-gateway 公司合作,您可能会使用 SMPP 协议(3.4 仍然是最常见的),然后看看 OpenSMPP 和 jSMPP。这些是与 SMPP 一起使用的强大库。
如果您要使用自己的硬件(例如 gsm-modem),发送消息最简单的方法是通过 AT 命令,它们因型号而异,因此,您应该了解支持哪些 AT 命令通过您的调制解调器。接下来,如果您的调制解调器有 IP 并且可以连接,您可以通过 java 套接字发送命令
Socket smppSocket = new Socket("YOUR_MODEM_IP", YOUR_MODEM_PORT);
DataOutputStream os = new DataOutputStream(smppSocket.getOutputStream());
DataInputStream is = new DataInputStream(smppSocket.getInputStream());
os.write(some_byte_array[]);
is.readLine();
否则你将通过COM端口工作,但方法相同(发送AT命令),你可以找到更多关于如何使用串口here的信息。
【讨论】:
有两种方法: 第一:使用需要付费的 SMS API 网关,也许你会找到一些试用版,甚至是免费的,但它很稀缺。 第二:使用AT命令与调制解调器GSM连接到您的笔记本电脑。 就是这样
【讨论】:
我在 Java 中见过的最好的 SMS API 是 JSMPP。它功能强大,易于使用,我自己将它用于企业级应用程序(每天发送超过 2 万条 SMS 消息)。
创建此 API 是为了减少现有 SMPP API 的冗长性。 它非常简单易用,因为它隐藏了复杂性 自动查询等低层协议通信 链接请求-响应。
我尝试过其他一些 API,例如 Ozeki,但其中大多数要么是商业 API,要么在其吞吐量方面存在限制(例如,每秒不能发送超过 3 条 SMS 消息)。
【讨论】:
您可以使用 LOGICA SMPP Java API 在 Java 应用程序中发送和接收 SMS。 LOGICA SMPP 是电信应用中经过充分验证的 api。 Logica API 还为您提供 TCP/IP 连接上的信令能力。
您可以直接与世界各地的各种电信运营商集成。
【讨论】:
TextMarks 让您可以访问其共享短代码,以通过其 API 从您的应用发送和接收短信。消息来自/发往 41411(而不是例如随机电话#,并且与电子邮件网关不同,您可以使用完整的 160 个字符)。
您还可以告诉人们将您的关键字输入到 41411 以调用您应用中的各种功能。有一个 JAVA API 客户端以及其他几种流行语言以及非常全面的文档和技术支持。
对于仍在测试和构建应用的开发者,可以轻松延长 14 天免费试用期。
在这里查看:TextMarks API Info
【讨论】:
如果您想要的只是简单的通知,许多运营商都支持通过电子邮件发送短信;见SMS through E-Mail
【讨论】: