无法使用HttpURLConnection

时间:2018-01-04 15:06:38

标签: android firebase-cloud-messaging httpurlconnection

我一直在看这一周,而且我无法找到空指针问题所在,这完全让我感到困扰,Google老师也不是很有帮助。我无法找到真正的问题......以及它的驱动坚果! :/

我正在尝试向Firebase发送通知,但它不会超出编写器,我已经检查过conn不是null或json,但它们看起来都很好。如果我使用RESTclient,我可以使用正确的ID密钥和消息成功发送消息,并由应用程序接收。模拟手机有互联网连接。

运行中抛出的错误如下所示:

  

com.android.okhttp.internal.huc.HttpURLConnectionImpl:https://fcm.googleapis.com/fcm/send。尝试调用接口方法' void om.android.okhttp.internal.http.HttpStream.writeRequestHeaders(com.android.okhttp.Request)'在null对象引用上。

我的代码:

            String FCM_URL = "https://fcm.googleapis.com/fcm/send";
            URL url = new URL(FCM_URL);     


            HttpURLConnection conn = (HttpURLConnection) url.openConnection();


            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            //set method as POST or GET
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(3000);
            //pass FCM server key
            conn.setRequestProperty("Authorization", "key=" + SERVER_KEY);

            //Specify Message Format
            conn.setRequestProperty("Content-Type", "application/json");

            conn.connect();


        //Create JSON Object & pass value
        JSONObject infoJson = new JSONObject();
        infoJson.put("body", message);
        infoJson.put("title", "Test send:");

        JSONObject json = new JSONObject();
        json.put("to", tokenId);
        json.put("collapse_key", "type_a");
        json.put("notification", infoJson);

        //Add data to json string
        JSONObject datacon = new JSONObject();
        datacon.put("body","First notification");
        datacon.put("title", "Collapsing A");
        datacon.put("key_1","Data for key 1");
        datacon.put("key_2","Hello, test two");

        json.put("data", datacon);


            BufferedWriter out =
                    new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
            out.write(json.toString());
            out.flush();
            out.close();

非常感谢任何帮助或指示!

1 个答案:

答案 0 :(得分:2)

似乎有一个错字,set而不是add

conn.setRequestProperty("Content-Type", "application/json");

之后,能够写

conn.connect();