You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用HttpURLConnection发送JSON至Firebase时遇空指针问题求助

Troubleshooting FCM Null Pointer in HttpStream.writeRequestHeaders

Hey there, sorry you’ve been stuck on this for a week—let’s break down what might be going on here. That null pointer on HttpStream.writeRequestHeaders is tricky, but since your REST client works, we know the FCM endpoint and credentials are valid. Here are targeted fixes and debugging steps to try:

1. Add Exception Handling & Debug Connection State

Your current code doesn’t catch exceptions during connection setup or stream handling, which might be hiding the root cause. Wrap the logic in a try-catch block and check the connection status before writing:

try {
    String FCM_URL = "https://fcm.googleapis.com/fcm/send";
    URL url = new URL(FCM_URL);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    
    // Your existing connection setup code
    conn.setUseCaches(false);
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setConnectTimeout(3000);
    conn.setRequestProperty("Authorization", "key=" + SERVER_KEY);
    conn.setRequestProperty("Content-Type", "application/json");
    
    conn.connect();
    
    // Debug: Verify connection status
    int responseCode = conn.getResponseCode();
    System.out.println("Connection Response Code: " + responseCode); // Should be 200-series before writing
    
    // Your JSON payload setup code
    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);
    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);
    
    // Explicitly set UTF-8 encoding (FCM requires this)
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
    out.write(json.toString());
    out.flush();
    out.close();
    
    // Check FCM response after sending
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String inputLine;
    StringBuilder response = new StringBuilder();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    System.out.println("FCM Response: " + response.toString());
    
} catch (Exception e) {
    e.printStackTrace(); // This will reveal hidden exceptions leading to the null pointer
}

The null pointer might occur because conn.getOutputStream() returns null due to a failed connection—but without exception handling, you won’t see the underlying error. Printing the response code and full stack trace will clarify this.

2. Explicitly Use UTF-8 Encoding

FCM requires JSON payloads in UTF-8. Your current OutputStreamWriter uses the platform’s default encoding, which might not match. Adding "UTF-8" to the constructor ensures the payload is formatted correctly, preventing silent failures that trigger the null pointer.

3. Double-Check SERVER_KEY Formatting

Even though your REST client works, it’s easy to accidentally copy extra whitespace or typos into your SERVER_KEY variable. Ensure the Authorization header is exactly:

conn.setRequestProperty("Authorization", "key=" + SERVER_KEY);

No spaces around the = sign, and no quotes around the key itself.

4. Switch to OkHttp Directly

The error references OkHttp’s internal classes—meaning your device uses OkHttp as the underlying implementation for HttpURLConnection. Switching to the OkHttp library directly avoids compatibility issues. Here’s a simplified example:

OkHttpClient client = new OkHttpClient();

MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(json.toString(), JSON);
Request request = new Request.Builder()
        .url("https://fcm.googleapis.com/fcm/send")
        .addHeader("Authorization", "key=" + SERVER_KEY)
        .post(body)
        .build();

try (Response response = client.newCall(request).execute()) {
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
    System.out.println(response.body().string());
} catch (Exception e) {
    e.printStackTrace();
}

This is more robust and handles connection details better than native HttpURLConnection.

5. Check ProGuard/R8 Obfuscation

If you’re using ProGuard or R8, it might be obfuscating OkHttp’s internal classes, leading to the null pointer. Add these rules to proguard-rules.pro:

-keep class com.android.okhttp.** { *; }
-keep interface com.android.okhttp.** { *; }
-keep class okhttp3.** { *; }
-keep interface okhttp3.** { *; }

Start with adding exception handling and checking the connection response code—this will likely reveal the hidden issue causing the null pointer. Let me know what the stack trace or response code shows!

内容的提问来源于stack exchange,提问作者user1501127

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:07:25