SMS 보내기

 | JAVA
2012. 5. 15. 18:35

HTTP POST 프로토콜로 모 휴대폰 문자 서비스 웹사이트로 자동접속 하여 휴대폰으로 문자 메시지를 보내 주는 소스 입니다.

고가의 SMS 단문메시지 전송 솔루션이 있지만 간단하게 웹사이트 장애나, 모니터링 용도로 자신의 시스템에 SMS 기능을 간단히 접목 시킬수 있습니다.

 

 

 

 

/**
 * @(#) SMS.java
 * Copyright 1999-2003 by  Java Service Network Community, KOREA.
 * All rights reserved.  http://www.javaservice.net
 *
 * NOTICE !      You can copy or redistribute this code freely,
 * but you should not remove the information about the copyright notice
 * and the author.
 *
 * @author  WonYoung Lee, javaservice@hanmail.net
 */
import java.net.*;
import java.io.*;
import java.util.StringTokenizer;
public class SMS {
    public final static String SERVER =  "www.smsphone.co.kr";
    public final static int PORT =  80;
    public static boolean TRACE = false;

    public static void main(String[] args) throws Exception
    {
        if ( args.length < 5 ) {
            System.out.println("Copyright 1999-2003 by  Java Service Network Community, KOREA.");
            System.out.println("All rights reserved. http://www.javaservice.net, javaservice@hanmail.net");
            System.out.println("Note: you shoud have id/passwd on http://www.smsphone.co.kr");
            System.out.println("      But, I hove no relationship with the SMSPHONE.co.kr web site.");
            System.out.println();
            System.out.println("Usage: java SMS <id> <passwd> <sender> <tolist> \"<message>\"");
            System.out.println("Ex: java SMS 0118987904 MyPasswd 0118987904 0118987904 재밌지?");
            System.out.println("Ex: java SMS 0118987904 MyPasswd 0118987904 0118987904;0118986266 \"햐~ 신기하지?\"");
            System.out.println("Ex: java -Dsms.trace=true SMS 0118987904 MyPasswd 0118987904 0118987904 \"trace할려구?\"");
            System.out.println("Ex: java -DproxySet=true -DproxyHost=proxy.our.com -DproxyPort=80 SMS \\");
            System.out.println("       0118987904 MyPasswd 0118987904 0118987904 \"프락시서버가 있다구?\"");
            System.out.println();
            System.exit(1);
        }
        if( "true".equals(System.getProperty("sms.trace"))) TRACE = true;
        sendsms(args[0], args[1], args[2], args[3],args[4]);
        System.out.println("Message sent to " + args[3] + " successfully.\n");
        System.out.println("Copyright 1999-2003 by  Java Service Network Community, KOREA.");
        System.out.println("All rights reserved. http://www.javaservice.net, javaservice@hanmail.net");
        System.out.println("Note: I hove no relationship with the SMSPHONE.co.kr web site.");
    }

    public static void sendsms(String id, String pwd, String returnphone, String tolist, String msg) throws Exception
    {
        if(TRACE) System.out.print("> login to http://" + SERVER + "/login_ok.asp");
        Socket socket =  new Socket(SERVER,PORT);
        if(TRACE) System.out.println("connected");
        InputStream in = null;
        OutputStream out = null;
        try{
            in = socket.getInputStream();
            out = socket.getOutputStream();
            //==========================================================
            // 1. login to www.smsphone.co.kr
            String sessionid = null;
            try{
                java.util.Hashtable data = new java.util.Hashtable();
                data.put("id", id); 
                data.put("pwd", pwd);
                //sessionid = http_post_send(in,out,"/login_ok.asp","",url_encoding(data),"parent.location.href='index.asp'");
            }
            catch(Exception e){
                throw new Exception( "login failed: " + e.toString());
            }

            //==========================================================
            // 2. SMS send to www.smsphone.co.kr
            try{
                java.util.Hashtable data = new java.util.Hashtable();
                data.put("mode", "1"); 
                data.put("ResGubn", "0");
    tolist = tolist.endsWith(";") ? tolist : tolist + ";"; // bug(?) patch ....
                data.put("SendList", tolist);
                data.put("SendLenCount", ""+(new StringTokenizer(tolist,";")).countTokens());
                data.put("returnNumber", returnphone);
                data.put("Message", msg);
                data.put("msgLen", ""+msg.getBytes().length );
                //http_post_send(in,out,"/send_msg.asp", sessionid, url_encoding(data),":"+id);
    System.out.println(data.toString());
            }
            catch(Exception e){
                throw new Exception( "login success but message send failed: " + e.toString());
            }
            //==========================================================
        }
        finally {
            if ( in != null ) try{in.close();}catch(Exception e){}
            if ( out != null ) try{out.close();}catch(Exception e){}
            if ( socket != null ) try{socket.close();}catch(Exception e){}
        }
    }

    private static String url_encoding(java.util.Hashtable hash){
        if ( hash == null ) throw new IllegalArgumentException("argument is null");
        java.util.Enumeration enum = hash.keys();
        StringBuffer buf = new StringBuffer();
        boolean isFirst = true;
        while(enum.hasMoreElements()){
          if (isFirst) isFirst = false;
          else buf.append('&');
          String key = (String)enum.nextElement();
          String value = (String)hash.get(key);
          buf.append(java.net.URLEncoder.encode(key));
          buf.append('=');
          buf.append(java.net.URLEncoder.encode(value));
        }
        return buf.toString();
    }
  

    public void setProxy(String host, String port, String id, String password) {
        // java -DproxySet=true -DproxyHost=proxy.our.com -DproxyPort=80 SMS \
        // Ex:       0118987904 MyPasswd 0118987904 0118987904 "프락시서버가 있다구?"
        java.util.Properties props = System.getProperties();
        props.put( "proxySet", "true" );
        props.put( "proxyHost", host );
        props.put( "proxyPort", port );
        System.setProperties(props);
        /*
        if ( id != null ) {
            String pw = id + ":" + password;
            String encodedPassword = com.sun.mail.imap.protocol.BASE64MailboxEncoder.encode( pw );
            httpURLConn.setRequestProperty( "Proxy-Authorization", encodedPassword );
        }
        */
    }

    private static String http_post_send(InputStream in, OutputStream out, String url, String sessionid, String body, String return_ok_str ) throws Exception
    {
        PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(out)));
        String header =
            "POST " + url + " HTTP/1.0\n" +
            //"Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*\n" +
            "Accept-Language: ko\n" +
            "Content-Type: application/x-www-form-urlencoded\n" +
            "Accept-Encoding: gzip, deflate\n" +
            "User-Agent: SMS_API(http://www.javaservice.net)\n" +
            "Host: " + SERVER + "\n" +
            "Content-Length: " + body.getBytes().length + "\n" +
            "Cookie: " + sessionid + "\n" +
            "Connection: Keep-Alive\n" +
            "Cache-Control: no-cache\n";
        if(TRACE){
          System.out.println("> -----------------------------------------------------------------------------");
          System.out.print(header);
          System.out.println(); // dummy line
        }
        pw.print(header);
        pw.println(); // dummy line
        pw.flush();

        if(TRACE) System.out.println(body);
        pw.print(body);
        pw.flush();
        if(TRACE){
          System.out.println("> -----------------------------------------------------------------------------");
          System.out.println("> header & data flushed");
          System.out.println("> now, wait response .....");
          System.out.println("> -----------------------------------------------------------------------------");
        }

        StringBuffer buf = new StringBuffer();
        int length = -1;
        String line = null;
        while( ( line = read_line(in)) != null ) {
            if(TRACE) System.out.println(line);
            if ( line.length() == 0 ) break;
            int x = line.indexOf("Content-Length:");
            if ( x > -1 ) {
                length = Integer.valueOf(line.substring(x+16)).intValue();
                if(TRACE) System.out.println("LENGTH:" + length);
            }
            int y = line.indexOf("Set-Cookie:");
            if ( y > -1 ) {
                sessionid = line.substring(y+12);
                int z = sessionid.indexOf("path");
                if ( z > -1 ) sessionid = sessionid.substring(0, z);
                if(TRACE) System.out.println("COOKIE:" + sessionid);
            }
        }
        if ( line == null ) throw new Exception("unexcepted header data format");

        if ( length != -1 ) {
            // (mayby) HTTP 1.1 "Content-Length" field exist in the header.
            byte[] d = read_data(in,length);
            buf.append(new String(d));
            if(TRACE) System.out.println(new String(d));
        }
        else {
            // NO "Content-Length" field exist in the header
            String length_hex = read_line(in);
            if ( length_hex == null ) throw new Exception("there is no HTTP body data");
            try{
                length = Integer.valueOf(length_hex.trim(),16).intValue();
            }
            catch(Exception e){
                //This means, the following data is just normal BODY data.
                //And length is still -1.
            }
            if ( length != -1 ) {
                // Yap. WebSphere 3.0.x, 3.5.x
                read_line(in); // dummy line
                byte[] d = read_data(in,length);
                buf.append(new String(d));
                if(TRACE) System.out.println(new String(d));
            }
            else {
                byte[] d = read_data(in);
                buf.append(new String(d));
                if(TRACE) System.out.println(new String(d));
            }
        }
        if( buf.toString().indexOf(return_ok_str) == -1) throw new Exception("No Excepted Result.\n"+ buf.toString());
        return sessionid;
    }
   
    public static final int INTPUTSTREAM_READ_RETRY_COUNT = 10;

    /**
     * The <code>read_data</code> method of <code>SocketUtil</code> reads the
     * specified length of bytes from the given input stream.
     *
     * @param      in   an inputstream
     * @param      len  the number of bytes read.
     * @return     The specified number of bytes read until the end of
     *             the stream is reached.
     * @exception  Exception  if an I/O error or unexpected EOF occurs
     */
    private static byte[] read_data(InputStream in, int len) throws Exception {
        java.io.ByteArrayOutputStream bout = new java.io.ByteArrayOutputStream();
        int bcount = 0;
        byte[] buf = new byte[2048];
        int read_retry_count = 0;
        while( bcount < len ) {
            int n = in.read(buf,0, len-bcount < 2048 ? len-bcount : 2048 );
            // What would like to do if you've got an unexpected EOF before
            // reading all data ?
            //if (n == -1) break;
            if ( n == -1 ) throw
                 new java.io.IOException("inputstream has returned an unexpected EOF");

            if ( n == 0 && (++read_retry_count == INTPUTSTREAM_READ_RETRY_COUNT) )
                throw new java.io.IOException("inputstream-read-retry-count( " +
                    INTPUTSTREAM_READ_RETRY_COUNT + ") exceed !");
            if ( n != 0 ) {
                bcount += n;
                bout.write(buf,0,n);
            }
        }
        bout.flush();
        return bout.toByteArray();
    }

    /**
     * The <code>read_data</code> method of <code>SocketUtil</code> reads all
     * the bytes from the given inputstream until the given input stream
     * has not returned an EOF(end-of-stream) indicator.
     *
     * @param      in   an inputstream
     * @return     all bytes read if the end of the stream is reached.
     * @exception  Exception  if an I/O error occurs
     */
    private static byte[] read_data(InputStream in) throws Exception {
        java.io.ByteArrayOutputStream bout = new java.io.ByteArrayOutputStream();
        int bcount = 0;
        byte[] buf = new byte[2048];
        int read_retry_count = 0;
        while( true ) {
            int n = in.read(buf);
            if (n == -1) break;
            if ( n == 0 && (++read_retry_count == INTPUTSTREAM_READ_RETRY_COUNT) )
                throw new java.io.IOException("inputstream-read-retry-count( " +
                    INTPUTSTREAM_READ_RETRY_COUNT + ") exceed !");
            if ( n != 0 ) {
                bcount += n;
                bout.write(buf,0,n);
            }
        }
        bout.flush();
        return bout.toByteArray();
    }
 
    /**
     * Read a line of text.  A line is considered to be terminated by a line
     * feed ('\n') or a carriage return followed immediately by a linefeed.
     *
     * @return     A String containing the contents of the line, not including
     *             any line-termination characters, or null if the end of the
     *             stream has been reached
     *
     * @exception  IOException  If an I/O error occurs
     */
    private static String read_line(InputStream in) throws Exception {
        java.io.ByteArrayOutputStream bout = new java.io.ByteArrayOutputStream();
        boolean eof = false;
        while( true ) {
            int b = in.read();
            if (b == -1) { eof = true; break;}
            if ( b != '\r' && b != '\n' ) bout.write((byte)b);
            if (b == '\n') break;
        }
        bout.flush();
        if ( eof && bout.size() == 0 ) return null;
        //Or return ""; ? what's fit for you?
        return bout.toString();
    }
}

이 글은 스프링노트에서 작성되었습니다.

'JAVA' 카테고리의 다른 글

String(문자열)내의 한글 확인  (0) 2012.05.15
Socket Simple 채팅 프로그램  (0) 2012.05.15
Printf 수식 모음  (0) 2012.05.15
passwd 암호화  (0) 2012.05.15
OS CPU MEMORY 값 보여주기  (0) 2012.05.15
Posted by 사라링
BLOG main image
.. by 사라링

카테고리

사라링님의 노트 (301)
JSP (31)
J-Query (41)
JAVA (24)
디자인패턴 (1)
스트러츠 (3)
안드로이드 (11)
오라클 (45)
우분투-오라클 (1)
이클립스메뉴얼 (6)
스프링3.0 (23)
자바스크립트 (10)
HTML5.0 (17)
정보처리기사 (1)
기타(컴퓨터 관련) (1)
문제점 해결 (3)
프로젝트 (2)
AJAX (4)
하이버네이트 (3)
트러스트폼 (11)
Jeus (2)
재무관리(회계) (5)
정규식 (5)
아이바티스 (8)
취미 (2)
소프트웨어 보안 관련모음 (0)
정보보안기사 (6)
C언어 베이직 및 프로그램 (3)
보안 관련 용어 정리 (2)
넥사크로 (6)
웹스퀘어_ (0)
Total :
Today : Yesterday :