Send Notification to Specific Topic in Firebase in Java - 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 .

Related

HttpURLConnection request showing up in Android Studio profiler but not reaching microcontroller

I'm trying to access a local IP using an Android app with HttpURLConnection. The web server is working, I tested it with Postman. Using a microcontroller I can see when someone connects to that IP address, so I know it's something in my app that's not working.
I have the app set up so that it sends a POST request, and when I press the button the Android Studio profiler detects the request and shows the IP address, but it won't reach the microcontroller.
String urlString = "http://192.168.2.115/request"; // URL to call
OutputStream out = null;
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.connect();
} catch (Exception e) {
return e.getMessage();
}
I enabled the INTERNET and the ACCESS_NETWORK_STATE permissions in AndroidManifest.xml and am not yet sending or receiving any data, just trying to access the IP address
Any help is appreciated, thank you!
Edit: It works now, I needed to add conn.getInputStream(); after conn.connect, for whatever reason
In which thread do you try to make http connection? Android system is prohibit to make network connection on main thread. Probably should use AsyncTask/RxJava/Thread.

Why Android HttpURLConnection is not able to create Asset on Azure Media Services using REST API?

I am trying to create an Asset on Azure Media Services using REST API from Android. I am following this documentation and this is my code to connect with AMS endpoint from Android,
urlConnection = (HttpURLConnection) this._url.openConnection();
urlConnection.setRequestProperty("Content-Type", String.valueOf("application/json"));
urlConnection.setRequestProperty("DataServiceVersion", String.valueOf("1.0;NetFx"));
urlConnection.setRequestProperty("MaxDataServiceVersion", String.valueOf("3.0;NetFx"));
urlConnection.setRequestProperty("Accept", String.valueOf("application/json"));
urlConnection.setRequestProperty("Accept-Charset", String.valueOf("UTF-8"));
urlConnection.setRequestProperty("Authorization", String.format(Locale.ENGLISH, "Bearer %s", _token));
urlConnection.setRequestProperty("x-ms-version", String.valueOf(2.11));
urlConnection.setRequestProperty("x-ms-client-request-id", UUID.randomUUID().toString());
urlConnection.setRequestProperty("Host", this._host);
urlConnection.setRequestProperty("Content-Length", String.valueOf(this._postData.length));
urlConnection.setRequestProperty("Expect", String.valueOf("100-continue"));
urlConnection.setConnectTimeout(CONNECTION_TIME_OUT);
urlConnection.setReadTimeout(CONNECTION_READ_TIME_OUT);
urlConnection.setInstanceFollowRedirects(true);
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
OutputStream wr= urlConnection.getOutputStream();
wr.write(_postData);
wr.flush();
wr.close();
And my _postData variable is byte array which I am converting from json,
_fileName = _fileName.replace(" ", "-");
JSONObject jo = new JSONObject();
jo.put("Name", _fileName+".mp4");
jo.put("Options", String.valueOf(0));
this._postData = jo.toString().getBytes("UTF-8");
I have tried using Google Chrome's REST api client extension to check the post request and It works fine. I got the response I was expecting from chrome's REST api client extension but using Android, I am not getting the same response. I am getting this response from this code which is the step I have already performed before running this code. I have used both endpoints https://media.windows.net/ and https://wamsbayclus001rest-hs.cloudapp.net/ but it is not working from Android. I believe that Android is changing Headers or something is wrong with headers that AMS not parsing properly. Can anyone guide me how to achieve this using Android HttpUrlConnection?
Thanks.
I fixed it by changing OutputStream to DataOutputStream
DataOutputStream wrr = new DataOutputStream(urlConnection.getOutputStream());
wrr.write(this._postData);
wrr.flush();
wrr.close();
and changed my json array to string,
String s = "{\"Name\":\"" + _fileName + ".mp4\", \"Options\":\"0\"}";
and it worked fine.

Firebase send server notification 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 ;)

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.

Categories

Resources