shrawan zadoo
shrawan zadoo

Reputation: 55

send push via urban airship using their web service (java)

I have gone through the post

The code works fine for me. i need to do this using java, i tried using the HttpURLConnection and the javax.xml.rpc.Service but no luck.

I need to know how to do the implementation using java.

Upvotes: 0

Views: 1937

Answers (1)

shrawan zadoo
shrawan zadoo

Reputation: 55

Solved it.

pushClient class:

public static void main(String[] args)
{
    try
    {
        String responseString = "";
        String outputString = "";
        String username = "Application Key";
        String password = "Application secret";
        Authenticator.setDefault(new MyAuthenticator(username,password));

        URL url = new URL("https://go.urbanairship.com/api/push/");
        URLConnection urlConnection = url.openConnection();
        HttpURLConnection httpConn = (HttpURLConnection)urlConnection;
        ByteArrayOutputStream bout = new ByteArrayOutputStream();

        String postdata = "{\"android\": {\"alert\": \"Hello from JAVA!\"}, \"apids\": [\"APID\"]}";
        byte[] buffer = new byte[postdata.length()];
        buffer = postdata.getBytes("UTF8");

        bout.write(buffer);
        byte[] b = bout.toByteArray();
        httpConn.setRequestProperty("Content-Length",String.valueOf(b.length));

        httpConn.setRequestProperty("Content-Type", "application/json");
        httpConn.setRequestMethod("POST");

        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);

        OutputStream out = httpConn.getOutputStream();
        out.write(b);
        out.close();

        InputStreamReader isr = new InputStreamReader(httpConn.getInputStream());
        BufferedReader in = new BufferedReader(isr);

        while ((responseString = in.readLine()) != null) 
        {
            outputString = outputString + responseString;
        }
        System.out.println(outputString);

    }
    catch (MalformedURLException e) 
    {
        e.printStackTrace();
    }
    catch (IOException e1) 
    {
        e1.printStackTrace();
    }
}

MyAuthenticator class:

    private String user;
    private String passwd;

    public MyAuthenticator(String user, String passwd)
    {
        this.user = user;
        this.passwd = passwd;
    }

    protected PasswordAuthentication getPasswordAuthentication()
    {
        return new PasswordAuthentication(user, passwd.toCharArray());
    }

Upvotes: 1

Related Questions