GCM + Android + Java help need - java

I am new in the Java Android world. I am working on a course project and I need some help. In my project I have developed an Android app and a Java Socket Server. Android App requests for Keys from Server and server generates keys, Stores them in its DB and sends keys back to android client. This is working fine. Now, in android client, I have to add a button called "Register Device" and on click this should register device with GCM and store the regID in device, which I want to add with keys request and send to server. Server will store the regID in DB with the keys. Then later I want to send a push message to device using that stored regID.
Problems:
How can I store and then access GCM regID to send to server?
What needs to be done in my Socket Server to send push messages to device using stored regID?

As I see you have obtained the deviceID and registrationID and you have to store it on your server.
Now can create a button which will do the following onclick.
$
public void sendRegistrationIdToServer(String deviceId,
String registrationId) {
HttpClient client = new DefaultHttpClient();
Log.d("GCM","sending to server");
HttpPost post = new HttpPost("YOur URL.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
// Get the deviceID
nameValuePairs.add(new BasicNameValuePair("deviceid", deviceId));
nameValuePairs.add(new BasicNameValuePair("registrationid", registrationId));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
Log.d("GCM","sent to server");
} catch (IOException e) {
e.printStackTrace();
}
}
And in the server side you can receive the ID's and store it in your database.
Hope you get it.

Related

Azure Event Hub Authorization from Android

I‘m working on an application that sends data to an azure event hub. This is similar to the blog post here:http://sreesharp.com/send-events-from-android-app-to-microsoft-azure-event-hubs/
However, I updated the connection code to use OkHttp:
public void sendMessageOkHttp(String dataPacket, String connectionString, String sasKey){
// Instantiate the OkHttp Client
OkHttpClient client = new OkHttpClient();
// Create the body of the message to be send
RequestBody formBody = new FormBody.Builder()
.add("message", dataPacket)
.build();
// Now create the request and post it
Request request = new Request.Builder()
.header("Authorization", sasKey)
.url(connectionString)
.post(formBody)
.build();
Log.i(TAG,"about to send message");
// Now try to send the message
try {
Log.i(TAG,"sending message....");
Response response = client.newCall(request).execute();
Log.i(TAG,"message sent");
Log.i("Azure Response",String.valueOf(response.message()));
// Do something with the response.
} catch (IOException e) {
e.printStackTrace();
}
}
However this returns a response from the event hub "Unauthorized". The sas key I am using is for a shared access policy that I created with send and listen permissions. It is the primary key.
What am I doing wrong here? The Azure documentation doesnt really help me in this case because it focused on using the Azure Java libraries that are not Android compatible (i.e. they require Java 1.8)
It's not the SAS Key you send in the Authorization header, it's the SAS Token. Here are like 5 or six different languages for generating the SAS Token from the key: https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-sas-overview

Sending an HTTP POST request in Java and accepting the POST request in PHP

What I need to do is send a username and password to a php script via a HTTP POST request so that I can query a database for the correct information. Currently I am stuck on both sending the POST request as well as receiving it.
To send a username and password I am using the following:
public class post {
public static void main(String[] args) throws ClientProtocolException, IOException {
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://www.example.com/practice.php");
// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("username", "user"));
params.add(new BasicNameValuePair("password", "hunter2"));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
//Execute and get the response.
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
try {
// do something useful
} finally {
instream.close();
}
}
}
}
The php script I am using to collect the information is the following, it's simple but it's just for testing at the moment.
<?php
$username = $_POST['username'];
$password = $_POST['password'];
echo "username = $username<br>";
echo "password = $password<br>";
?>
I was wondering if someone could help me out by moving me in the correct direction of accepting a HTTP POST request in php from Java, or if I am even sending the post request correctly, any help is greatly appreciated.
Now, there are a few things, I would suggest you to keep in mind, while doing this.
Try Making use of JSON:
Json stands for JavaScript Object Notation. Itis a lightweight, text-based, language-independent data exchange format that is easy for humans and machines to read and write.
public static void main(String[] args){
JSONObject obj = new JSONObject();
obj.put("username", username);
obj.put("password", password);
System.out.print(obj);
// And then, send this via POST Method.
}
}
For Php part,
...
$data = file_get_contents("php://input");
$json = json_decode($data);
$username = $json['username'];
$password = $json['password'];
...
Here is a good reference for that Json
Make Use of Sessions When you work with an application, you open it, do some changes, and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are or what you do, because the HTTP address doesn't maintain state.
Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser.
<?php
$_SESSION["user"] = "green";
echo "Session variables are set.";
// Now store this in your database in a separate table and set its expiry date and time.
?>
Here is a reference to that as well sessions.
Use SSL : Secure Socket Layer (SSL) technology is security that is implemented at the transport layer.SSL allows web browsers and web servers to communicate over a secure connection. In this secure connection, the data that is being sent is encrypted before being sent and then is decrypted upon receipt and before processing. Both the browser and the server encrypt all traffic before sending any data. SSL addresses the following important security considerations.
a. Authentication: During your initial attempt to communicate with a web server over a secure connection, that server will present your web browser with a set of credentials in the form of a server certificate. The purpose of the certificate is to verify that the site is who and what it claims to be. In some cases, the server may request a certificate that the client is who and what it claims to be (which is known as client authentication).
b. Confidentiality: When data is being passed between the client and the server on a network, third parties can view and intercept this data. SSL responses are encrypted so that the data cannot be deciphered by the third party and the data remains confidential.
c. Integrity: When data is being passed between the client and the server on a network, third parties can view and intercept this data. SSL helps guarantee that the data will not be modified in transit by that third party.
And, Here are a few references for that as well.
SSL Establishment Documentation, SSL with Java

Android phone use Java to send a textfile to hosted webspace

I want to save a message in a text file on an android phone onto a hosted web server like bluehost of which I have a username and password. I want to store the file in an arbitrary directory on the server.
What are the general strategies that this could be accomplished? I want to use the HTTP protocol, is that a good idea? Is there a better way?
You can try to POST that string to the server:
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.com");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("yourVarName", stringVar);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
return (response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 204);
} catch (ClientProtocolException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
Transmit a file from an android phone to hosted web space
You import the JSCH jars into your Android application, then you load up the JSCH manager classes and use the defined functions to transmit or receive files between an android phone and hosted webspace.
Run a command over SSH with JSch
JSCH has FTP functionality where you can transmit from phone to hosted web space and will work as long as the hosted web space is reachable by the phone. You can also do the same thing in reverse.

determine aplication is connected to server or not

I am developing one application which is connecting to server to get some data.
In this I want to check first if application is connected to server or not. And then, if server is on or off? Based on the result I want to do my further manipulations.
So how do I get the result of server status?
Here is the code which I am using:
Code:
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://192.168.1.23/sip_chat_api/getcountry.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
}
Maintaining session cookies is best choice here, please see how to use session cookie: How do I make an http request using cookies on Android?
here, before sending request to server, check for session cookie. If it exists, proceed for the communication.
Update:
The Java equivalent -- which I believe works on Android -- should be:
InetAddress.getByName(host).isReachable(timeOut)
Check getStatusLine() method of HttpResponse
any status code other than 200 means there is a problem , and each status codes points to different problems happened.
http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/HttpResponse.html?is-external=true
http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/StatusLine.html#getStatusCode()

How to send a string to a php file from Android?

I have a php script on a local server that creates and manages an SQL table. I am able to create the table and database through my android app but I am having trouble figuring out how to send data to the php file. I want to send a string so that I can sort and pick the values to return to my app.
How do I change my php and android code so that I can get entries in the table between 2 dates?
Here is some of my Android code:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.0.3/xampp/information.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
The beginning of information.php script is setup like this:
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("data",$con);
How do I send a string from Android to the php file?
You should try using $_POST variables. So your HttpPost object would be initialized like this:
HttpPost httppost = new HttpPost("http://10.0.0.3/xampp/information.php?info="+nameValuePairs);
Then, in your PHP, just check to see if the variable info is set, and then process it if it is.
if(isset(_$POST['info']))
//process data
This would, of course, requiring some formatting of nameValuePairs so that it is a valid URL, but it forces everything into one variable which you can easily check in your PHP.

Categories