Java JSON Example

From SMS Wiki
Jump to: navigation, search

Below is sample code for Java programmers. You are welcome to cut+paste this sample into your application, however, keep in mind that depending on your environment, some changes may be required.


Note: In order to run this sample, you need include MOXy library, as well as JAXB if no built-in JAXB in your JDK

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
 
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.transform.stream.StreamSource;
 
import org.eclipse.persistence.jaxb.JAXBContextProperties;
import org.eclipse.persistence.jaxb.xmlmodel.ObjectFactory;
 
public class TestUpsideRESTAPIJSON {
 
	public static final String APIEndPoint = "https://secureapi.upsidewireless.com"; // or "http://api.upsidewireless.com"
	public static final String APICredential_Token ="xxxxxxxx-8e4b-405b-998c-a580bf593b76";
	public static final String APICredential_Signature = "xxxxxxxxfyqQx95Gxxxxxxxx";
 
	private static String SMSMsgUrl = String.format("%s/RESTv1/%s/Message", APIEndPoint, APICredential_Token);
 
	public static void main(String[] argv) throws Exception {
		HttpURLConnection connection = null;
        boolean acceptJSON = true;
 
        System.out.println("SMS Message URL: " + SMSMsgUrl);
 
        try {
            URL smsMessageUrl = new URL(SMSMsgUrl);
            connection = (HttpURLConnection)smsMessageUrl.openConnection();
 
    		connection.setRequestMethod("POST");
    		connection.setRequestProperty("Content-Type", "application/json");
    		connection.setRequestProperty("Accept", acceptJSON ? "application/json" : "application/xml");
    		connection.setRequestProperty("User-Agent", "UpsideJavaAgent");
    		connection.setConnectTimeout(100 * 1000); // 100 seconds
    		connection.setReadTimeout(300 * 1000); // 300 seconds
    		connection.setDoOutput(true);
 
            String type = "sms"; // see type list on wiki
            String message = "test sms message";
            String recipient = "16047891236"; // number in E.164 format
            String encoding = "7"; // 7, 8 or 16
 
            String jsonObject = "{signature:\"" + APICredential_Signature + "\"";
            jsonObject += ",type:\"" + type + "\"";
            jsonObject += ",message:\"" + message + "\"";
            jsonObject += ",recipient:\"" + recipient + "\"";
            jsonObject += ",encoding:\"" + encoding + "\"}";
 
    		PrintWriter pw = new PrintWriter(connection.getOutputStream());
    		pw.println(jsonObject);
    		pw.close();
 
			InputStream input = null;
			try {
				input = connection.getInputStream();
			} catch (Exception e) {
				input = connection.getErrorStream();
			}
			StringBuffer sbResponse = new StringBuffer(1024);
			BufferedReader reader = new BufferedReader(new InputStreamReader(input));
			String inputLine = null;
			while ((inputLine = reader.readLine()) != null) {
				sbResponse.append(inputLine);
			}
			reader.close();
 
			String responseString = sbResponse.toString();
			System.out.println("REST Response: " + responseString);
 
			RestResponse restResponse = null;
			if (acceptJSON) {
		        Map<String, Object> properties = new HashMap<String, Object>(2);
		        properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
		        properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
		        JAXBContext jaxbContext = JAXBContext.newInstance(new Class[] {RestResponse.class, ObjectFactory.class}, properties);
		        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
		        StringReader sr = new StringReader(responseString);
		        StreamSource json = new StreamSource(sr);
		        restResponse = unmarshaller.unmarshal(json, RestResponse.class).getValue();
 
				// or use your favourite method to parse JSON object
			} else {
		        JAXBContext jaxbContext = JAXBContext.newInstance(RestResponse.class);
		        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
		        StringReader sr = new StringReader(responseString);
		        restResponse = (RestResponse) unmarshaller.unmarshal(sr);
 
				// or use your favourite method to parse XML object
			}
 
            if (restResponse != null)
            {
            	System.out.println("Rest Response - HasException: " + restResponse.isHasException());
            	System.out.println("Rest Response - Token: " + restResponse.getToken());
                if (restResponse.isHasException())
                {
                	System.out.println("Rest Response - RestException.ErrorCode: " + restResponse.getRestException().getErrorCode());
                	System.out.println("Rest Response - RestException.Message: " + restResponse.getRestException().getMessage());
                    if (restResponse.getRestException().getStatus() != null)
                    	System.out.println("Rest Response - RestException.Status: " + restResponse.getRestException().getStatus());
                }
                else
                {
                	System.out.println("Rest Response - SMSMessage.Status: " + restResponse.getSMSMessage().getStatus());
                	System.out.println("Rest Response - SMSMessage.Recipient: " + restResponse.getSMSMessage().getRecipient());
                	System.out.println("Rest Response - SMSMessage.Body: " + restResponse.getSMSMessage().getBody());
                	System.out.println("Rest Response - SMSMessage.Type: " + restResponse.getSMSMessage().getType());
                	System.out.println("Rest Response - SMSMessage.TrackingId: " + restResponse.getSMSMessage().getTrackingId());
                    if ("REJECTED".equals(restResponse.getSMSMessage().getStatus()))
                    	System.out.println("Rest Response - SMSMessage.RejectReason: " + restResponse.getSMSMessage().getRejectReason());
                }
            }
            else
            {
            	System.out.println("Can't get rest response object");
            }
 
        } catch (Exception e) {
        	System.out.println("Error in calling API - " + e.getMessage());
        	e.printStackTrace();
        } finally {
			if (connection != null) {
				connection.disconnect();
			}
        }
	}
}
 
 
@XmlRootElement(name="RestResponse")
@XmlAccessorType(XmlAccessType.FIELD)
class RestResponse
{
	@XmlElement(name = "HasException")
    private boolean HasException;
	@XmlElement(name = "Token")
    private String Token;
 
	@XmlElement(name = "SMSMessage")
    private SMSMessage SMSMessage;
	@XmlElement(name = "RestException")
    private RestException RestException;
 
	public boolean isHasException() {
		return HasException;
	}
 
	public void setHasException(boolean hasException) {
		HasException = hasException;
	}
 
	public String getToken() {
		return Token;
	}
 
	public void setToken(String token) {
		Token = token;
	}
 
	public SMSMessage getSMSMessage() {
		return SMSMessage;
	}
 
	public void setSMSMessage(SMSMessage sMSMessage) {
		SMSMessage = sMSMessage;
	}
 
	public RestException getRestException() {
		return RestException;
	}
 
	public void setRestException(RestException restException) {
		RestException = restException;
	}
}
 
@XmlAccessorType(XmlAccessType.FIELD)
class SMSMessage
{
	@XmlElement(name = "Status")
    private String Status;
	@XmlElement(name = "Recipient")
    private String Recipient;
	@XmlElement(name = "Body")
    private String Body;
	@XmlElement(name = "Type")
    private String Type;
	@XmlElement(name = "TrackingId")
    private String TrackingId;
	@XmlElement(name = "RejectReason")
    private String RejectReason;
 
	public String getStatus() {
		return Status;
	}
 
	public void setStatus(String status) {
		Status = status;
	}
 
	public String getRecipient() {
		return Recipient;
	}
 
	public void setRecipient(String recipient) {
		Recipient = recipient;
	}
 
	public String getBody() {
		return Body;
	}
 
	public void setBody(String body) {
		Body = body;
	}
 
	public String getType() {
		return Type;
	}
 
	public void setType(String type) {
		Type = type;
	}
 
	public String getTrackingId() {
		return TrackingId;
	}
 
	public void setTrackingId(String trackingId) {
		TrackingId = trackingId;
	}
 
	public String getRejectReason() {
		return RejectReason;
	}
 
	public void setRejectReason(String rejectReason) {
		RejectReason = rejectReason;
	}
 
}
 
@XmlAccessorType(XmlAccessType.FIELD)
class RestException
{
	@XmlElement(name = "ErrorCode")
    private int ErrorCode;
	@XmlElement(name = "Message")
    private String Message;
	@XmlElement(name = "Status")
    private String Status;
 
	public int getErrorCode() {
		return ErrorCode;
	}
 
	public void setErrorCode(int errorCode) {
		ErrorCode = errorCode;
	}
 
	public String getMessage() {
		return Message;
	}
 
	public void setMessage(String message) {
		Message = message;
	}
 
	public String getStatus() {
		return Status;
	}
 
	public void setStatus(String status) {
		Status = status;
	}
}