itsource

어떻게 자바에 문자를 보내기.

mycopycode 2022. 9. 21. 00:01
반응형

어떻게 자바에 문자를 보내기.

무엇이 가능한 방법 통해서 자바 응용 프로그램에서 sms 보내 줄까?

어떻게?

(Disclaimer:나는 Twilio에서 일해)

Twilio은 Twilio REST의 API를 SMS전송하는 자바 SDK을 제공한다.

만약 당신이 간단하다 알림 원한다면, 많은 통신사 이메일을 통해;e메일을 통해 SMS를 보SMS를 지지한다.

한 API라는 SMSLib, 정말 놀라운 건.http://smslib.org/

이제 여러분은 이 서비스가 그들의 API를 사용을 줄 수 있Saas 제공자들이 많다.

Ex:mailchimp, esendex, Twilio,...

가장 좋은 SMSAPI나는 자바에서 본 거 JSMPP.그것은, 사용하기 편하며 저 자신이enterprise-level 응용 프로그램( 두고 하루 20K 문자 메세지를 보내는)에 사용했던 강력하다.

이 API는 기존 SMPP API의 용장을 줄이는 것입니다.때문에 자동으로 문의하다 링크 request-response 같은 수준이 낮고 프로토콜 통신의 복잡성을 숨기고 매우 쉽게 사용하기에 매우 간단합니다.

나는, 그러나 그들의 대부분은 억누르거나 혹은 처리량(i.e는 1초에 예를 들어 이상 3문자 메세지를 보낼 수 없어)에 한계를 가지고 있는 상업적인 있는 일부 다른 APIsOzeki 같은 시도해 봤다.

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

Nexmo를 이용하여 SMS를 보내고 SMS를 받을 수 있습니다.

Nexmo Java Library에서 SMS를 보내는 것은 매우 간단합니다.신규 계정 생성, 가상 번호 대여, API 키 및 비밀 취득 후 라이브러리를 사용하여 다음과 같이 SMS를 보낼 수 있습니다.

  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를 수신하려면 웹 훅을 사용하는 서버를 설정해야 합니다.그것도 꽤 간단합니다.자바에서 SMS를 수신하는 튜토리얼을 확인해 보시기 바랍니다.

공개:저는 넥스모에서 일하고 있습니다.

TextMarks는 API를 통해 앱과 문자 메시지를 주고받을 수 있는 공유 쇼트코드에 대한 액세스를 제공합니다.메시지는 41411 로부터 송신됩니다(랜덤 전화번호가 아니고, 전자 메일게이트웨이와는 달리, 풀 160 문자를 사용할 수 있습니다).

또한 앱의 다양한 기능을 호출하기 위해 키워드를 41411로 입력하도록 사람들에게 지시할 수 있습니다.JAVA API 클라이언트와 기타 일반적인 언어, 매우 포괄적인 문서 및 기술 지원이 있습니다.

14일 무료 평가판은 아직 테스트 중이고 앱을 만들고 있는 개발자들에게 쉽게 연장할 수 있습니다.

여기를 봐주세요.TextMarks API 정보

두 가지 방법이 있습니다.첫 번째: 비용을 지불해야 하는 SMS API 게이트웨이를 사용하세요.아마 무료 체험판을 찾을 수 있을 것입니다만, 희소합니다.두 번째 : 노트북에 연결된 모뎀 GSM에서 AT 명령어를 사용하는 경우.그것뿐입니다.

OMK.smpp. API. SMPP 기반이며 시뮬레이터도 무료로 이용할 수 있습니다.

LOGICA SMPP API

또 다른 옵션은 무료 WAP 및 SMS 게이트웨이 Kannel입니다.

Twilio와 같은 클라우드 기반 솔루션을 제안합니다.클라우드 기반 솔루션은 지속적인 유지보수가 필요하지 않으므로 사내 솔루션보다 비용 효율이 높습니다.이메일을 통한 SMS는 사용자로부터 통신사 정보를 얻어야 하고 모든 휴대 전화 번호를 문자로 보낼 수 있는지 확신할 수 없기 때문에 우아한 해결책이 아닙니다.웹 어플리케이션에서 twilio java api를 사용하여 서버사이드에서 sms를 보내고 있습니다.몇 분 안에 앱과 통합할 수 있습니다.

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 어플리케이션에서 SMS 송수신 시 LOGICA SMPP Java API를 사용할 수 있습니다.LOGICA SMPP는 통신 어플리케이션에서 입증된 API입니다.Logica API는 TCP/IP 접속에서의 시그널링 기능도 제공합니다.

전 세계의 다양한 통신 사업자와 직접 통합할 수 있습니다.

작업 방식 및 공급업체에 따라 다릅니다.

만약 당신이 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 명령 전송). 시리얼 포트 사용 방법에 대한 자세한 내용은 여기를 참조하십시오.

Twilio를 사용하면 됩니다.그러나 까다로운 회피책을 찾고 있다면 아래에 언급한 회피책을 따라갈 수 있습니다.

SMS를 수신할 수 없습니다.그러나 이는 다수의 클라이언트에 SMS를 보낼 때 사용할 수 있는 까다로운 방법입니다.twitter API를 사용할 수 있습니다.우리는 휴대폰에서 문자메시지로 트위터 계정을 팔로우 할 수 있습니다.트위터로 문자만 보내면 돼.사용자 이름으로 Twitter 계정을 만든다고 가정해 보십시오.@username그러면 아래와 같이 40404로 sms를 보낼 수 있습니다.

follow @username

그 후, 트윗이 그 어카운트에 트윗이 올라옵니다.

트위터 계정을 만든 후 Twitter API를 사용하여 해당 계정에서 트윗을 게시할 수 있습니다.그러면 아까 말씀드린 것처럼 그 계정을 팔로우한 모든 고객이 트윗을 받기 시작합니다.

twitter API로 트윗을 올리는 방법은 다음 링크에서 배울 수 있습니다.

트위터 API

개발을 시작하기 전에 twitter api 사용 허가를 받아야 합니다.다음 링크에서 twitter api에 접속할 수 있습니다.

트위터 개발자 콘솔

이것은 당신의 문제에 대한 최선의 해결책이 아닙니다.하지만 이게 도움이 되길 바라.

또한 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 요구를 송신할 때 문제가 있는 경우는, 다음의 질문을 참조해 주세요.

구체적인 경우 SMPP API를 사용하는 것도 고려할 수 있으며 이미 언급한 JSMPP 라이브러리가 도움이 됩니다.

그곳에는 오감도서관이 있다.SMS를 송신하는 코드는 쓰기 쉽다(문자 부호화, 메시지 분할을 자동적으로 처리한다).실제 SMS는 SMPP 프로토콜(표준 SMS 프로토콜)을 사용하거나 공급자를 통해 전송됩니다.실제 SMS 전송 비용을 지불하기 전에 SMPP 서버에서 코드를 로컬로 테스트하여 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]
    }
}

에도 많은 특징과 샘플/스프링 샘플이 있습니다.

GSM 모뎀을 사용한SMS 송신에는 AT&T 명령어를 사용할 수 있습니다.

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

반응형