Firebase send server notification java - java

So, I saw this question using Jersey. But still didn't figure out how to send a simple push notification from my server to topic subscribed users.
I don't understand what's wrong in my request as I am trying to build based on their examples.
public class OverSLANotifier {
public static void main(String[] args) throws Exception, FirebaseException {
String rawData = "{\"to\": \"/topics/sla\",\"data\": {\"message\": \"This is test push notification!\",}}";
String encodedData = URLEncoder.encode(rawData, "UTF-8");
URL u = new URL("https://fcm.googleapis.com/fcm/send");
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "key=AI<redacted>VGB6YwPWrinoz1YFBgdKv4Pgm8s");
conn.setRequestProperty("Content-Type", "application/json");
OutputStream os = conn.getOutputStream();
os.write(encodedData.getBytes());
System.out.println(""+ conn.getResponseCode() + "-->>"+conn.getResponseMessage());
}
My client is properly set and can receive if I send from console.
The response is always:
401-->>Unauthorized

you're json seems invalid:
{\"to\": \"/topics/sla\",\"data\": {\"message\": \"This is test push notification!\",}}
vs
{\"to\": \"/topics/sla\",\"data\": {\"message\": \"This is test push notification!\"}}
Also check the documentation:
The sender account used to send a message couldn't be authenticated.
Possible causes are:
Authorization header missing or with invalid syntax in HTTP request.
Invalid project number sent as key.
Key valid but with FCM service disabled.
Request originated from a server not whitelisted
in the Server key IPs.
Source
PS: its also invalid in the documentation youll find here ;)

Related

Failing to send JSON data using POST-method and HTTPS to Webserver with Java

Currently I'm trying to address a webserver using HTTPS and POST method and send a JSON file to this server. I have already tried several tutorials but unfortunately I can only find examples for HTTP and Post and not HTTPS. Did I forget to implement something?
I would like to provide the code of the server, but I only received the address and the format of the JSON files.
Has anyone had the problem before or can help me?
Thank you
public static void main(String[] args) throws IOException {
URL url = new URL(" https://webservice.com:1234");
HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setRequestProperty("Accept", "application/json");
//con.setDoInput(true);
con.setDoOutput(true);
String jsonInputString = "\"ID\": \"12\"";
System.out.println(jsonInputString);
try(OutputStream os = con.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
os.flush();
}
System.out.println(con.getResponseCode());
Unfortunately I always get this error message:
Exception in thread "main" javax.net.ssl.SSLException: Unsupported or
unrecognized SSL message at
java.base/sun.security.ssl.SSLSocketInputRecord.handleUnknownRecord(SSLSocketInputRecord.java:439)
at
java.base/sun.security.ssl.SSLSocketInputRecord.decode(SSLSocketInputRecord.java:184)
at
java.base/sun.security.ssl.SSLTransport.decode(SSLTransport.java:108)
at
java.base/sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1180)
at
java.base/sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocketImpl.java:1091)
at
java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:402)
at
java.base/sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:567)
at
java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:187)
at
java.base/sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1362)
at
java.base/sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1337)
at
java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:247)
at test.main(test.java:40)
Process finished with exit code 1
Sometimes the https returns SSL errors if the service is not secure. This happens a lot in localhost or some servers with only http. Maybe try removing the 's'
Many thanks for all your help, in a discussion with the developer of the web service I was able realize that the server does not support HTTPS. That means the link to the server was wrong - http//: instead of https//:
So with the HttpURLConnection con = (HttpURLConnection)url.openConnection(); it works just fine.

Send Notification to Specific Topic in Firebase in Java

Hi I'm trying to send firebase message from java code , and I have done this from the console and its working and I'm receiving Notification on My Devices , and also I have sent messages through java to specific Devices via token and its working too , and I'm having trouble sending ones to topic , I get no error and no exception from server side but nothing is received on devices.
here's the code I'm using to send Requests to firebase :
String authKey = AUTH_KEY_FCM; // You FCM AUTH key
String FMCurl = API_URL_FCM;
URL url = new URL(FMCurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization","key="+authKey);
conn.setRequestProperty("Content-Type","application/json");
JSONObject json = new JSONObject();
json.put("to","/topics/all");
JSONObject data = new JSONObject();
data.put("message",title);
json.put("data", data);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(json.toString());
wr.flush();
conn.getInputStream();
}
as you can see the inner object in the Json is Data with param "message" like the one provided on google docs , I've also tried replacing it with "notification" with "body" and "title" as its working for sending messages to specific devices via token but again not working for topics.
and again its not needed to mention that everything on the android side is working cause it works sending Topic Message through firebase console
UPDATE : this method is working and I have to Handle it to actually show the notification when the message is Received .
Thanks for your helps in advance.
this method is working now and have to handle it to actually show the notification when the message is received on the device .

send http request from IIS to GCM using java

I am trying to send Json message from my [java application server] to [GCM]:
the java server app located on IIS server (Windows server 2008 R2).
here is my function:
public static String post(String apiKey, String json){
try{
URL url = new URL("https://android.googleapis.com/gcm/send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type:", "application/json");
conn.setRequestProperty("Authorization:", "key="+apiKey); // apiKey is valid browser apiKey.
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeUTF(json);
wr.flush();
wr.close();
/*I've deleted the respond check from the question*/
}
but I fail to send!, and does not get any message or exception.
I think that the server itself doesnt let me send http requests!
is this true? how to solve?
I recommend using the Sender and Message objects instead. The sample GCM server code uses those. Sample server code can be seen here.
If you really insist on handling the connection yourself, you can look at the underlying HttpURLConnection implementation of the Sender object here.
It does appear that there are certain differences between the Sender code and your request properties. Hope this helps.

HTTP Post in C2DM giving SocketTimeoutException

I made an app. for Android which uses the C2DM service from Google. I
made a server simulator from some tutorials and it works fine. My
problem is, I tried to build a Java Servlet. From the Android device
it receives fine the message and saves the Registration ID, but when I
try to send a https POST request to the Google C2DM Server it always
gets a SocketTimeoutException : Timeout while fetching:
https://android.clients.google.com/c2dm/send.
I don't get why this is happening when the same works on the Android
device. Here is the code:
//The AuthToken from Google Client Login
String auth_key = TOKEN;
StringBuilder postDataBuilder = new StringBuilder();
//some parameters to pass, I've checked and it's correct, it's working
//with Fiddler
postDataBuilder.append(PARAM_REGISTRATION_ID).append("=").append(REGISTRATION_ID);
postDataBuilder.append("&").append(PARAM_COLLAPSE_KEY).append("=").append("0");
postDataBuilder.append("&").append("data.payload").append("=").append(URLEncoder.encode(message, UTF8));
byte[] postData = postDataBuilder.toString().getBytes(UTF8);
URL url = new URL("https://android.clients.google.com/c2dm/send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestProperty("Content-Length",Integer.toString(postData.length));
conn.setRequestProperty("Authorization", "GoogleLogin auth="+auth_key);
OutputStream out = conn.getOutputStream();
out.write(postData);
out.close();
int responseCode = conn.getResponseCode();
//here comes the error processing, but I can't reach it, because of
//the exception.
if (responseCode == 401 || responseCode == 403) {
//....
}
Thanks for your help :).
The first obvious thing to check is - if you have thought of this I apologise - are you behind a proxy server e.g. a company firewall? If so a timeout is exactly the symptom I'd expect with the above code. (This catches me out all the time!)
With the latter half of your code (from the HttpURLConnection declaration on), unmodified, I see a timeout; on my system (behind a company firewall), with two changes I get a 200 OK back:
addition of a proxy object passed to the HttpUrlConnection factory as follows:
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("...", 8080));
HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);
accepting the C2DM server's certificate that wasn't trusted by my JVM. For test purposes I overrode the default hostname verifier and TrustManager as described in Trusting all certificates using HttpClient over HTTPS . For production you should look at a more secure solution.
Another thing I spotted; it doesn't seem to matter but http://code.google.com/android/c2dm/index.html#push says to post to https://android.apis.google.com/c2dm/send, not android.clients.google.com - just something to be aware of that might break in future.
I faced same problem and
I had tried :
URL url = new URL("http://android.apis.google.com/c2dm/send");
instead of :
URL url = new URL("https://android.apis.google.com/c2dm/send");
it worked for me.

Java http call returning response code: 501

I am having an issue with this error:
**Server returned HTTP response code: 501 for URL: http://dev1:8080/data/xml/01423_01.xml**
See this code:
private static Map sendRequest(String hostName, String serviceName) throws Exception {
Map assets = null;
HttpURLConnection connection = null;
Authenticator.setDefault(new Authenticator());
URL serviceURL = new URL(hostName + "/" + serviceName);
connection = (HttpURLConnection)serviceURL.openConnection();
connection.setRequestMethod("GET");
ClientHttpRequest postRequest = new ClientHttpRequest(connection);
InputStream input = null;
/*
At line input = postRequest.post(); I get the following error
Server returned HTTP response code: 501 for URL: http://dev1:8080/data/xml/01423_01.xml
Yet if I enter that url in my browser it opens up fine.
Is this a common problem? Is there some type of content type I need to set?
*/
input = postRequest.post();
connection.disconnect();
return assets;
}
A 501 response means "not implemented", and is usually taken to mean that the server didn't understand the HTTP method that you used (e.g. get, post, etc).
I don't recognise ClientHttpRequest , but you have a line that says
connection.setRequestMethod("GET");
and then a line that says
input = postRequest.post();
I'm not sure what post() actually does, but does that mean send a POST request? If so, then that contradicts the GET specified in the first line.
Either way, the server is saying that it doesn't under the GET or the POST method, whichever one your code is actually sending. You need to find out what method the server does support for that URL, and use that.
Perhaps you should check your port settings:
new URL(hostName + "/" + serviceName);
Looks like the port number ":8080" is missing.
Some server expect additional information from the client in the request like a user agent or some form data. Even cookies could be expected by the application running on the server. You should also check the complete response and not only the response code.
I would recommend you to use a library like httpclient that is more convenient:
https://hc.apache.org/httpcomponents-client-ga/index.html
Here is simple usage example:
https://github.com/apache/httpcomponents-client/blob/master/httpclient5/src/test/java/org/apache/hc/client5/http/examples/ClientWithResponseHandler.java

Categories

Resources