отправить толчок через городской дирижабль, используя их веб-сервис (Java) - PullRequest
0 голосов
/ 18 января 2012

Я прошел через сообщение

Код прекрасно работает для меня. Мне нужно сделать это с помощью Java, я пытался использовать HttpURLConnection и javax.xml.rpc.Service, но не повезло.

Мне нужно знать, как сделать реализацию с использованием Java.

1 Ответ

1 голос
/ 19 января 2012

Решил это.

класс pushClient:

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:

    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());
    }
...