1

我遵循了 UA 教程并获得了我的 APID,并在我的 android 设备上成功收到了测试推送消息。

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

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

java.io.IOException:服务器返回 HTTP 响应代码:URL 401: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) at 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();
    }
}

}

你能帮我吗 ?

4

1 回答 1

0

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

于 2012-01-29T11:05:44.597 回答