gpt4 book ai didi

java - Urban Airship 推送码

转载 作者:行者123 更新时间:2023-12-01 05:30:34 24 4
gpt4 key购买 nike

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

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

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

java.io.IOException: Server returned HTTP response code: 401 for 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) 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();
}
}

}

你能帮我吗?

最佳答案

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

关于java - Urban Airship 推送码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9052496/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com