Programming

Java로 SMS를 보내는 방법

procodes 2020. 7. 10. 21:33
반응형

Java로 SMS를 보내는 방법


Java 응용 프로그램에서 SMS를 보내고받을 수있는 방법은 무엇입니까?

어떻게?


(면책 조항 : Twilio에서 일합니다)

Twilio는 Twilio REST API를 통해 SMS를 전송하기위한 Java SDK제공합니다 .


간단한 알림 만 원하는 경우 많은 이동 통신사가 이메일을 통해 SMS를 지원합니다. 이메일을 통한 SMS 참조


SMSLib라는 API가 있는데 정말 끔찍합니다. http://smslib.org/

편집하다:

이제 API를 사용하여이 서비스를 제공 할 수있는 많은 Saas 제공 업체가 있습니다.

예 : mailchimp, esendex, Twilio, ...


Java에서 본 최고의 SMS API는 JSMPP입니다. 강력하고 사용하기 쉬우 며 엔터프라이즈 수준의 응용 프로그램에 매일 사용했습니다 (매일 20K 이상의 SMS 메시지 전송).

이 API는 기존 SMPP API의 세부 정보를 줄이기 위해 작성되었습니다. 링크 요청-응답 자동 조회와 같은 저수준 프로토콜 통신의 복잡성을 숨기므로 매우 간단하고 사용하기 쉽습니다.

Ozeki와 같은 다른 API를 사용해 보았지만 대부분 상용이거나 처리량이 제한적입니다 (예 : 1 초에 3 개 이상의 SMS 메시지를 보낼 수 없음).


GSM 모뎀과 Java Communications API를 사용하여이 작업을 수행 할 수 있습니다.

  1. 먼저 Java Comm Api를 설정해야합니다.

    이 기사에서는 통신 API를 설정하는 방법에 대해 자세히 설명합니다.

  2. 다음 당신은 GSM 모뎀이 필요합니다 (바람직하게는 sim900 모듈)

  3. Java JDK 최신 버전 선호

  4. 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");
           }
         }
    
    
            }
    

You can use Nexmo to send SMS as well as receive SMS.

Sending SMS with the Nexmo Java Library is fairly straightforward. After creating a new account, renting a virtual number, and getting your API key & secret you can use the library to send SMS like so:

  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);
          }
      }
  }

To receive SMS you'll need to set up a server that consumes a webhook. That's fairly simple as well. I recommend checking out our tutorial on receiving SMS with Java.

Disclosure: I work for Nexmo


TextMarks gives you access to its shared shortcode to send and receive text messages from your app via their API. Messages come from/to 41411 (instead of e.g. a random phone# and unlike e-mail gateways you have the full 160 chars to work with).

You can also tell people to text in your keyword(s) to 41411 to invoke various functionality in your app. There is a JAVA API client along with several other popular languages and very comprehensive documentation and technical support.

The 14 day free trial can be easily extended for developers who are still testing it out and building their apps.

Check it out here: TextMarks API Info


You can you LOGICA SMPP Java API for sending and Recieving SMS in Java application. LOGICA SMPP is well proven api in telecom application. Logica API also provide you with signalling capicity on TCP/IP connection.

You can directly integrate with various telecom operator accross the world.


There are two ways : First : Use a SMS API Gateway which you need to pay for it , maybe you find some trial even free ones but it's scarce . Second : To use AT command with a modem GSM connected to your laptop . that's all


It depends on how you're going to work and who your provider is.

If you work with a sms-gateway company you'll probably work through SMPP protocol (3.4 is still the most common), then have a look on OpenSMPP and jSMPP. These are powerful libs to work with SMPP.

If you're going to work with your own hardware (f.e. a gsm-modem) the easiest way to send messages is through AT commands, they differ depends on the model, so, you should find out what AT commands is supported by your modem. Next, if your modem has an IP and open to connection, you can send commands through java socket

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();

Otherwise you'll work through a COM port, but the method is the same (sending AT commands), you can find more information how to work with serial ports here.


OMK.smpp. API. it's base on SMPP and simulator is also available for free

LOGICA SMPP API.

And another option is Kannel a free WAP and SMS gateway.


I suggest a cloud based solution like Twilio. Cloud based solutions are cost-effective, than an in-house solution as the there is no ongoing maintenance, required. SMS through email is not an elegant solution, as you have to get the carrier information from the user and you can never be sure that you can text all mobile numbers. I am using twilio java api in my web application, to send sms from serverside. within few minutes, you can integrate with your app.

https://www.twilio.com/docs/java/install

Here's an example sending an SMS message from the docs:

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());
  }
}

smslib is very useful for this purpose u can connect a modem with Your pc and use this lib to send sms . It works I have used it


We also love Java in Wavecell, but this question can be answered without language-specific details since we have a REST API which will cover most of your needs:

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!" }'

Look at this questions if you have problems with sending HTTP requests in Java:

For specific cases you can also consider using the SMPP API and already mentioned JSMPP library will help with that.


You can use AT & T commands for sending sms using GSM modem.

참고URL : https://stackoverflow.com/questions/2570410/how-to-send-sms-in-java

반응형