How to send android push notification from website chat - java

I have completed programming a website chat like whatsapp design and I have created application in android. The app browser this website chat (only show website like chrome browser).
I need help to understand how can I get notification on my application when user get message The android notification should show "you have new message".
My question is how I can send data from website to android using push notification
The website chat

Your android application should be GCM registered and then you can send a GCM from your website which will then be pushed to your application.
For more details see : https://developer.android.com/google/gcm/client.html
For detailed tutorial see : http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/

public function notificationToAndroidAction($pushId){
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => array($pushId),
'data' => array("message" => 'hello!'),
);
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarily
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return 'sent';
}

Related

firebase - php - send notification to everyone

I want to send a background notification from fcm to all my users. This is my code, the only problem I've faced is that I have to put a token id. I need to send notification to all of my users without defining the token values
This is my code :
<?php
define('API_ACCESS_KEY','Api');
$fcmUrl = 'https://fcm.googleapis.com/fcm/send';
$token='token';
$notification = [
'title' =>'title',
'body' => 'body of message.',
'icon' =>'myIcon',
'sound' => 'mySound'
];
$extraNotificationData = ["message" => $notification,"moredata" =>'dd'];
$fcmNotification = [
//'registration_ids' => $tokenList, //multple token array
'to' => $token, //single token
'notification' => $notification,
'data' => $extraNotificationData
];
$headers = [
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$fcmUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fcmNotification));
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>
It works fine and send notifications successfully, but how can I send notification to everyone?
It looks like there is no such feature to send notifications to all devices.
However, there is a workaround for your problem using topics. For this you will need to subscribe all users to a specific topic during the app startup.
FirebaseMessaging.getInstance().subscribeToTopic("your_topic");
Then you can send the notification to that topic so that the notification will be sent to all users.
'to' => '/topics/your_topic', // using topic instead of token
If i get your question.
You need to subscribe a Topic and then you just need to use that Topic.
The users who subscribed to it, will get the notification.
Docs:-
Based on the publish/subscribe model, FCM topic messaging allows you to send a message to multiple devices that have opted in to a particular topic. You compose topic messages as needed, and FCM handles routing and delivering the message reliably to the right devices.
https://firebase.google.com/docs/cloud-messaging/android/topic-messaging
There are two ways to send notification to multiple users.
Create a topic with all the users in it and send the push to that topic.
Example: https://firebase.google.com/docs/cloud-messaging/android/send-multiple
Send notification to application the package id. But this will send notification even to the non authenticated user.

Recieve variables in java Web Service from php cURL using POST?

I'm recieving 'null' on my Params.
So far i've found people using "PathParams", "FormParams" and "QueryParams" on java to get their variables from the request, however in my case, using post i dont have PathParams, and for some reason FormParams and QueryParams are returning null as if i had never sent them. So i'd like help to solve this.
My php cURL POST request:
<?php
$url = "http://localhost:8080/TestRest/test/asd";
$params = "param1=val1&param2=val2";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>
My java Web Service:
#Path("/test")
public class Streams {
#POST
#Path("/asd")
#Produces(MediaType.TEXT_PLAIN)
#Consumes({"application/x-www-form-urlencoded"})
public String addStream(#FormParam("param1") String param1,
#FormParam("param2") String param2) {
return "param1 = "+param1;
}
}
For some reason param1 is null.
What am i doing wrong?
I am going out on a limb and saying your problem may stem from this:
urlencode($params);
For instance: a=1&b=2&c=3 is perfectly valid.
urlencode('a=1&b=2&c=3') goes to this: a%3D1%26b%3D2%26c%3D3 and your webservice may not understand what it is your are passing. It is looking for a=...&b=...&c=... and you are not giving it any of that.
Try leaving off the urlencode() and seeing if it works. If it does, and you still want to ensure content like this&this is encoded properly, then you will need to parse the url parameters, encode them, and then recombine them for the post data.

How do I emulate a PHP cURL request in Java?

$ch = curl_init();
curl_setopt($ch, CURLOPT_FILE, $file);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $urls[$vidCount]);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_exec($ch);
curl_close($ch);
So I have a cURL request that takes a URL and produces a file in the filesystem.
How do I emulate the above PHP cURL request in Java?
I have tried HttpURLConnection, but I am getting 403 Forbidden. The same call in cURL works properly. Is there some architecture difference between the two that I need to reconcile?
I believe it could be something in the headers that cURL might be setting automatically where Java is not. I'm not really sure but I would appreciate any advice I can get.
Thanks.
I am not sure why you trying to emulate PHP behavior in Java. If the end result is really what you need to reach, than use the Java HttpURLConnection or even URLConnection.

POST data from PHP and GET data in java servlet

is there any method that I can retrieve data (eg, username and password) from PHP to a Java servlet? Thanks
Create a POST request in PHP:
Use cURL:
$ch = curl_init('http://www.example.com:8080/my-servlet/');
$data = '...' # the data you want to send
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
A better, more concise approach, using pecl_http:
$response = http_post_data('http://www.example.com:8080/my-servlet/', $data);
POST and GET pretty much do not depend on the language being used, so if I understand your question correctly, you can use either $_POST['var'] in PHP or request.getParameter("var") in Java on the page that receives the POST data.

POST from PHP to another (Java) web service and retrieving the (image) result

These are the steps:
POST Form (file/image input) from the browser goes to a PHP server.
The PHP server then use fsockopen to a Java (GlassFish/Jersey) REST service, sending the image as content for more advanced imaging work to be done there, and returning the resulting image back to the PHP server (or returning only a URI to the image).
The PHP server then echos the result (img src= ..) back to the user in the HTML document.
Getting the image and all its attributes in the first step works great, but I need help setting up the headers correctly in the POST request from PHP to the web service.
Current code:
$fp = fsockopen("domain..", 80, $errno, $errstr, 30);
$contentlength = $_FILES["photo_file"]["size"];
$imageref = $_FILES["photo_file"]["tmp_name"];
$out = "POST /Uri to resource .. HTTP/1.1\r\n";
$out .= "Host: http://... \r\n";
$out .= "Connection: Keep-Alive\r\n";
$out .= "Content-type: multipart/mixed\r\n";
$out .= "Content-length: $contentlength\r\n\r\n";
$out .= "$imageref";
fwrite($fp, $out);
$theOutput;
while (!feof($fp))
{
$theOutput .= fgets($fp, 128);
}
echo $theOutput;
fclose($fp);
Which echoes to the browser: "HTTP/1.1 400 Bad Request Content-Type: text/html Content-Length: 717".
So I need better formed headers to get through to the REST web-method. And if I should achieve that does anyone know what paramaters to use in the jersey web-method to access the image?
For standard HTML forms its this:
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response getFullImage(#FormDataParam("photo_file") InputStream imageIS {..ImageIO.read(imageIS)..}
Would love suggestions to better architecture also for achieving this in HTML.
Cheers
You probably have problem with badly written request and should use cURL at first place (in php), basic example usage (with writing to the file) from manual page:
$ch = curl_init("http://www.example.com/");
$fp = fopen("example_homepage.txt", "w");
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
Another example for setting post data from curl_setopt() page:
$data = array('name' => 'Foo', 'file' => '#/home/user/test.png');
curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
And handling HTTP status codes via curl_getinfo():
if(curl_getinfo($c, CURLINFO_HTTP_CODE) === 200){
...
}
You also may set http headers manually:
curl_setopt($cURL,CURLOPT_HTTPHEADER,array (
"Content-Type: text/xml; charset=utf-8",
"Expect: 100-continue"
));

Categories

Resources