import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
mapper.getFactory().configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true);
ObjectNode messages = mapper.createObjectNode();
messages.put("text", "Message via API");
messages.put("type", "alert");
messages.put("sender", "");
ObjectNode recipients = mapper.createObjectNode();
recipients.put("value", "33612345678");
ObjectNode sms = mapper.createObjectNode();
ObjectNode data = mapper.createObjectNode();
ArrayNode numero = mapper.createArrayNode();
ObjectNode gsm = mapper.createObjectNode();
numero.add(recipients);
gsm.set("gsm",numero);
sms.set("message",messages);
sms.set("recipients",gsm);
data.putPOJO("sms",sms);
String payload = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(data);
try {
Main hce = new Main();
String response = hce.post("https://api.smsfactor.com/send", payload);
System.out.println(response);
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
public String post(String postUrl, String data) throws IOException {
URL url = new URL(postUrl);
String token = "your.token";//Your first token must be generated on our plateform at https://my.smsfactor.com/developers/api-tokens
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Authorization","Bearer " + token);
con.setDoOutput(true);
this.sendData(con, data);
return this.read(con.getInputStream());
}
protected void sendData(HttpURLConnection con, String data) throws IOException {
DataOutputStream wr = null;
try {
wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(data);
wr.flush();
wr.close();
} catch(IOException exception) {
throw exception;
} finally {
this.closeQuietly(wr);
}
}
private String read(InputStream is) throws IOException {
BufferedReader in = null;
String inputLine;
StringBuilder body;
try {
in = new BufferedReader(new InputStreamReader(is));
body = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
body.append(inputLine);
}
in.close();
return body.toString();
} catch(IOException ioe) {
throw ioe;
} finally {
this.closeQuietly(in);
}
}
protected void closeQuietly(Closeable closeable) {
try {
if( closeable != null ) {
closeable.close();
}
} catch(IOException ex) {
}
}
}