Urban Airship推送代码

时间:2012-01-29 10:34:21

标签: java post urbanairship.com

我已经按照UA教程获得了我的APID,并在我的Android设备上成功收到测试推送消息。

现在我要做的下一件事是使用JAVA定位我的设备并发送推送消息。 从我目前所见,实现这一目标的最佳方法是使用他们的网络API。

但是,当我尝试发送帖子时,我总会收到以下错误:

  

java.io.IOException:服务器返回HTTP响应代码:401为URL:https://go.urbanairship.com/api/push/       at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)       at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)       在com.Sender.Sender.main(Sender.java:56)

这是我使用的代码:

package com.Sender;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class Sender {

/**
 * @param args
 */
public static void main(String[] args) {
    try {
        String responseString = "";
        String outputString = "";
        String username = "MWMoRVhmRXOG6IrvhMm-BA";
        String password = "ebsJS2iXR5aMJcOKe4rCcA";

        MyAuthenticator ma= new MyAuthenticator(username, password);

        Authenticator.setDefault(ma);

        URL url = new URL("https://go.urbanairship.com/api/push/");
        URLConnection urlConnection = url.openConnection();
        HttpURLConnection httpConn = (HttpURLConnection) urlConnection;
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        String APID = "23eef280-19c8-40fc-b798-788f50e255a2";

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

}

你能帮我吗?

1 个答案:

答案 0 :(得分:0)

HTTP 401表示未经授权的访问。在您的代码中,即使您创建了Authenticator,也没有将其作为post请求标头的一部分提供。这是关于如何为URLConnection设置authenticator 的教程。