1

我正在尝试使用 HttpsUrlConnection(java 代码)连接到 APNS(https://api.development.push.apple.com/)。我已经从https://api.development.push.apple.com/下载了证书并添加到 java 密钥库。

代码:

public class HttpsUrlConnectionClient {

    public static void main(String[] args) {

        {
            try {
                URL obj = new URL("https://api.development.push.apple.com/3/device/<device-token>");
                HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
                con.setRequestMethod("POST");
                con.setRequestProperty("apns-topic", "<apns-topic-name>");
                con.setRequestProperty("authorization", "bearer <apns-auth-key>");
                con.setRequestProperty("content-type", "application/json");
                con.setDoOutput(true);
                DataOutputStream wr = new DataOutputStream(con.getOutputStream());
                wr.writeBytes("{ \"aps\" : { \"alert\" : \"Hello\" } }");
                wr.flush();
                wr.close();

                int responseCode = con.getResponseCode();
                System.out.println(responseCode);


                BufferedReader in = new BufferedReader(
                        new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();


            } catch (Exception e) {

            }

        }
    }
}

我按照https://github.com/escline/InstallCert中提到的步骤获取服务器证书并在本地存储。

我总是将 responseCode 设为 -1(无效的 http 响应)。

请帮助我,因为我不明白这是由于证书还是其他原因。

4

0 回答 0