Пример работы с SMS шлюзом на языке Java

Класс API.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package sms.api.v2;
 
import java.util.ArrayList;
import java.util.Map;
 
public class API {
         
    private sms.api.v2.RequestBuilder reqBuilder;
    private String login;
    private String password;
 
    public API(sms.api.v2.RequestBuilder reqBuilder,String login, String password) {
        this.reqBuilder = reqBuilder;
        this.login=login;
        this.password=password;
    }
     
     
    public String getStatus(String msgId){
        String request="<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        request=request.concat("<SMS><operations><operation>GETSTATUS</operation></operations>");
        request=request.concat("<authentification>");
        request=request.concat("<username>"+this.login+"</username>");
        request=request.concat("<password>"+this.password+"</password>");
        request=request.concat("</authentification>");
        request=request.concat("<statistics>");
        request=request.concat("<messageid>"+msgId+"</messageid>");
        request=request.concat("</statistics>");
        request=request.concat("</SMS>");
        return this.reqBuilder.doXMLQuery(request);
    }
     
    public String getPrice(String text, Map<String, String>  phones){
        String request="<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        request=request.concat("<SMS>");
        request=request.concat("<operations>  ");
        request=request.concat("<operation>GETPRICE</operation>");
        request=request.concat("</operations> ");
        request=request.concat("<authentification>");
        request=request.concat("<username>"+this.login+"</username>");
        request=request.concat("<password>"+this.password+"</password>");
        request=request.concat("</authentification>");
        request=request.concat("<message>");
        request=request.concat("<sender>SMS</sender>");
        request=request.concat("<text>"+text+"</text>");
        request=request.concat("</message>");
        request=request.concat("<numbers>");
        for (Map.Entry entry : phones.entrySet()) {
            request=request.concat("<number messageID=\""+entry.getKey()+"\">"+entry.getValue()+"</number>");
        }
        request=request.concat("</numbers>");
        request=request.concat("</SMS>");
        return this.reqBuilder.doXMLQuery(request);
    }
     
    public String getBalance(){
        String request="<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        request=request.concat("<SMS>");
        request=request.concat("<operations>");
        request=request.concat("<operation>BALANCE</operation>");
        request=request.concat("</operations>");
        request=request.concat("<authentification>");
        request=request.concat("<username>"+this.login+"</username>");
        request=request.concat("<password>"+this.password+"</password>");
        request=request.concat("</authentification> ");
        request=request.concat("</SMS>");
        return this.reqBuilder.doXMLQuery(request);
    }
     
     public String sendSms(String sender, String text, ArrayList<Phones> phones){
        String request="<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        request=request.concat("<SMS>");    
        request=request.concat("<operations>");
        request=request.concat("<operation>SEND</operation>");
        request=request.concat("</operations>");
        request=request.concat("<authentification>");
        request=request.concat("<username>"+this.login+"</username>");
        request=request.concat("<password>"+this.password+"</password>");
        request=request.concat("</authentification>");
        request=request.concat("<message>");
        request=request.concat("<sender>"+sender+"</sender>");
        request=request.concat("<text>"+text+"</text>");
        request=request.concat("</message>");
        request=request.concat("<numbers>");
        for (Phones phone : phones) {
           request=request.concat("<number");
           if(phone.getIdMessage().length()>0) request=request.concat(" messageID=\""+phone.getIdMessage()+"\"");
           if(phone.getVariable().length()>0) request=request.concat(" variables=\""+phone.getVariable()+"\"");
           request=request.concat(">");
           request=request.concat(phone.getPhone());
           request=request.concat("</number>");
        }
        
        request=request.concat("</numbers>");
        request=request.concat("</SMS>");
        return this.reqBuilder.doXMLQuery(request);
     }
}

Класс Connector.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package sms.api.v2;
 
import java.io.IOException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
 
public class Connector {
 
    private static HttpURLConnection httpConn;
 
    private String URL;
 
    public Connector(String URL) {
        this.URL = URL;
    }
 
    /**
     * Makes an HTTP request using POST method to the specified URL.
     * @param params A map containing POST data in form of key-value pairs
     * @return An HttpURLConnection object
     * @throws IOException thrown if any I/O error occurred
     */
    public static HttpURLConnection sendPostRequest(String requestURL, Map<String, String> params) throws IOException {
        URL url = new URL(requestURL);
        httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setUseCaches(false);
        httpConn.setDoInput(true); // true indicates the server returns response
 
        StringBuffer requestParams = new StringBuffer();
 
        if (params != null && params.size() > 0) {
            httpConn.setDoOutput(true); // true indicates POST request
            Iterator<String> paramIterator = params.keySet().iterator();
            boolean isFirst=true;
            while (paramIterator.hasNext()) {
                String key = paramIterator.next();
                String value = params.get(key);
                if(!isFirst){  requestParams.append("&");}
                requestParams.append(key);
                requestParams.append("=").append(URLEncoder.encode(value,"UTF-8"));
                isFirst=false;
            }      
            // sends POST data
            OutputStreamWriter writer = new OutputStreamWriter(httpConn.getOutputStream());
            //URLEncoder.encode(requestParams.toString(),"UTF-8")
            writer.write(requestParams.toString());
            writer.flush();
        }
 
        return httpConn;
    }
 
    /**
     * Returns only one line from the server's response. This method should be
     * used if the server returns only a single line of String.
     *
     * @return a String of the server's response
     * @throws IOException thrown if any I/O error occurred
     */
    public static String readSingleLineRespone() throws IOException {
        InputStream inputStream = null;
        if (httpConn != null) {
            inputStream = httpConn.getInputStream();
        } else {
            throw new IOException("Connection is not established.");
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                inputStream));
 
        String response = reader.readLine();
        reader.close();
 
        return response;
    }
 
    /**
     * Returns an array of lines from the server's response. This method should
     * be used if the server returns multiple lines of String.
     *
     * @return an array of Strings of the server's response
     * @throws IOException thrown if any I/O error occurred
     */
    public static String[] readMultipleLinesRespone() throws IOException {
        InputStream inputStream = null;
        if (httpConn != null) {
            inputStream = httpConn.getInputStream();
        } else {
            throw new IOException("Connection is not established.");
        }
 
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                inputStream));
        List<String> response = new ArrayList<String>();
 
        String line = "";
        while ((line = reader.readLine()) != null) {
            response.add(line);
        }
        reader.close();
 
        return (String[]) response.toArray(new String[0]);
    }
 
    /**
     * Closes the connection if opened
     */
    public static void disconnect() {
        if (httpConn != null) {
            httpConn.disconnect();
        }
    }
}

Класс Phones.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package sms.api.v2;
 
 
public class Phones {
    public String idMessage;
    public String varaibles;
    public String phone;
    
    public Phones(String idMessage,String variables,String phone){
        this.phone=phone;
        this.varaibles=variables;
        this.idMessage=idMessage;
    }
     
    public String getIdMessage(){
        return this.idMessage;
    }
     
    public String getVariable(){
        return this.varaibles;
    }
     
    public String getPhone(){
        return this.phone;
    }
     
}

Класс RequestVuilder.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package sms.api.v2;
 
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
 
public class RequestBuilder {
     
    String URL;
 
    public RequestBuilder(String URL) {
        this.URL = URL;
    }
     
    public String doXMLQuery(String xml) {
        StringBuilder responseString = new StringBuilder();
          
        Map <string, string="">  params=new HashMap();
        params.put("XML", xml);
        try {
            Connector.sendPostRequest(this.URL, params);
            String[] response = Connector.readMultipleLinesRespone();
            for (String line : response) {
             responseString.append(line);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        Connector.disconnect();
        return responseString.toString();       
    
}
</string,>

Пример использования:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package sms.api.v2;
 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
 
public class Test {
   public static void main(String[] args) {
      String login="YOUR_LOGIN";
      String password="YOUR_PASSWORD";
       
      RequestBuilder Request= new RequestBuilder(URL);
      API ApiSms=new API(Request, login, password);
       
       
      //GET STATUS *************************************************************
      System.out.print(ApiSms.getStatus("1299"));
      /*
       * response: <?xml version="1.0" encoding="UTF-8"?>
            <deliveryreport><message id="1299" sentdate="0000-00-00 00:00:00" donedate="0000-00-00 00:00:00" status="0" /></deliveryreport>
      */
       
      //GET PRICE *************************************************************
      Map<String, String>  phones = new HashMap();
      phones.put("id1", "+38063169****");
      phones.put("id2", "+38093101****");
      System.out.print(ApiSms.getPrice("Test sms",phones));
      /*
       * response: <?xml version="1.0" encoding="UTF-8"?><RESPONSE><status>0</status><credits>0.682</credits></RESPONSE>
      */
       
       
      //GET BALANCE *************************************************************
      System.out.print(ApiSms.getBalance());
      /*
       * response: <?xml version="1.0" encoding="UTF-8"?><RESPONSE><status>0</status><credits>780.64</credits></RESPONSE>
      */
   
      //SEND PHONE *************************************************************
      ArrayList<Phones> phoneSend=new ArrayList<Phones>();
      phoneSend.add(new Phones("id1","","+38063169****"));
      phoneSend.add(new Phones("id2","","+38093101****"));
  
      System.out.print(ApiSms.sendSms("test", "test sms", phoneSend));
      /*
       * response: <?xml version="1.0" encoding="UTF-8"?><RESPONSE><status>2</status><credits>0.682</credits></RESPONSE>
      */
   }   
}

vector
image

Нужна помощь?

Задайте вопрос специалисту технической поддержки