Stream Data to Website from Android device - android

For a project I would like to stream the sensor data of an Accelerometer (from an android phone) to a website.
Basically I have written the application that reads the data and stores it on the phone and converts it to a string. I just want to plot the x, y and z Values as line graph dynamically on a website. So If I shake my phone, the line on the website should be moving.
I had several ideas like using Node.js or Java webserver but I couldn't found any appropriate tutorials.
So maybe someone got a good idea where to find tutorials, where I can learn how to stream data to a website from my phone. It should be easy to do or not that hard but I am not very good in making webservers or so.

Keep sending your data to the server ideally making post request.
Your webserver can just read the data from the obtained requests and update the graph.
How to write a server ? go through the below link
http://tutorials.jenkov.com/java-multithreaded-servers/singlethreaded-server.html
how to post data from android ? use an async task doing the below things
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.server.com/");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("graphvalue", "12345"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}

Related

How can I pass data from my android application and receive it on my ASP.NET MVC website?

I want to send the some varibeles from my android application to my ASP.NET website, so I can use it there and I don't know how to do that.
If your ASP.NET application has some type of public API that would allow it to interact with external applications, you should be able to make a Web Request to it and post the appropriate values that you needed.
I'm not terribly familiar with Android syntax, but an example like this one on making HTTP GET/POST requests from Android should point you in the right direction :
// Build your client
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("your-asp-mvc-application/Home/AcceptData");
// Build a collection of data that you want to send
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("username", "test_user"));
nameValuePair.add(new BasicNameValuePair("password", "123456789"));
// Encoding POST data
try
{
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
}
catch (UnsupportedEncodingException e) {
// log exception
e.printStackTrace();
}
// Make the request
try
{
HttpResponse response = httpClient.execute(httpPost);
// write response to log
Log.d("Http Post Response:", response.toString());
}
catch (ClientProtocolException e)
{
// Log exception
e.printStackTrace();
}
catch (IOException e)
{
// Log exception
e.printStackTrace();
}
Basically, once you make make requests, you should be able to target your application and create a Controller Action that can actually accept what you are sending it :
public ActionResult AcceptData(string username, string password)
{
// Do something here
}
First, what form of ASP.NET are you using - Forms or MVC? Also, what do you mean by "send?" Where exactly do you want the data to end up and what exactly do you want your ASP.NET application to do once it receives the data? If you simply mean that you're creating data in your phone and you want your ASP.NET web site to be able to access it too, you can just insert the data into a database that your ASP.NET web site also has access to (e.g. through a web service call or something like that).

Android authentication using JSON

I have a Python/Django server that is the API for a web service.
I'm building an Android application that will communicate with the API and authenticate users, and enable them do all pulls/pushes from the server.
My trouble is with the particular communication with the server. Currently I use my WiFi network, and run the server like so python manage.py runserver 192.168.1.3:8000 so that it is available to any test device on my LAN.
The API is written so it returns http status messages with every response, so that I can tell the success or failure of a request before parsing the JSON reply.
On my Android side, I have used HttpURLConnection because it has the getHeaderField(null) method that I use to pick the http status message from the response. I get a status message 200 [success] when I 'ping' my server - this is a sort-of proof of concept.
My real issue is authentication. My API requires I send it a JSON with data, and it returns a JSON response [with an http status message in the head].
I can't seem to figure out how to do this. The JSON action I've seen around the interwebs are merely picking, or posting.
I am wondering how I can POST and pick up a response from the server.
Extra information
- Server supports HEAD and GET and OPTIONS.
- Assuming server home is 192.168.1.3, user login/register would be in 192.168.1.3/user, events would be in 192.168.1.3/events and so on..
- This was the closest I got to figuring out a solution, but not quite..
CODE from the AsyncTask
protected JSONObject doInBackground(String... params) {
publishProgress(true);
/*Create a new HttpClient and Post Header*/
JSONObject result=null;
HttpClient httpclient = new DefaultHttpClient();
try {
URL url = new URL(cons.PROTOCOL,cons.SERVER,cons.PORT,"/user");
HttpPost httppost = new HttpPost(url.toURI());
HttpResponse response =null;
/*Add your data*/
JSONObject j1=new JSONObject();
JSONObject json=new JSONObject();
j1.put("username", "test");
j1.put("email","test#test.com");
j1.put("password","password");
j1.put("first_name","John");
j1.put("last_name","Doe");
json.put("user",j1);
json.put("mobile_number","256774622240");
StringEntity se = new StringEntity( json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
/*Execute HTTP Post Request*/
response= httpclient.execute(httppost);
Log.i("jazz","It's ALIVE!!!!!");
Log.i("jazz",response.getStatusLine().toString());
} catch (ClientProtocolException e) {
/* TODO Auto-generated catch block*/
} catch (IOException e) {
// TODO Auto-generated catch block
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
If your are building your HttpPostRequest well, and you only want to know how to attach JSON, here you are a possible solution for it:
StringEntity formEntity = new StringEntity(yourJsonObject.toString());
yourPostRequest.setEntity(formEntity);
I hope this helps!
PS:In addition, let me recommend you the use of this component:
https://github.com/matessoftwaresolutions/AndroidHttpRestService
I've used it in an Android app that is connecting to a python server API and it makes http request easier for your Android client.
Okay, so I'm now answering my own question :D
The issue was with the path variable in the URL string.
This is the format of one of the URL constructors based on this document.
URL(String protocol, String host, int port, String file)
Since I am posting the JSON to the /user path, that's the one I insert into the constructor as the directory.
So, my URL was formed like so:
URL url= new URL("http",cons.SERVER,cons.PORT,"/user/");
My mistake in the beginning was using /user instead of /user/
but other than that, the URL structure and connections are all alright.

Is there any way to create a mini-proxy for http on android?

I am working on a HttpClient that posts something to a website. The client looks something like this (based on this link):
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
What I want to do now is to create a small proxy service (a VERY simple one) that runs on the same android device and listens for the outgoing HTTP connexions and modifies the POST ( for example change the "id": "12345" into "54321", just for testing purposes), and then pass the HttpRequest to the actual website. How cand I do something like that? I've been googling around but found nothing that could give me an idea how to do it(like a tutorial or something). Can anybody give me an idea of how to do that?
You do not need to write code to achieve this. Instead of writing your own proxy and since you only need it to test you application, you can use the mitmproxy which is a man-in-the-middle proxy (based on your description that is what you want to achieve). Follow this tutorial to set up your PC as the proxy and the device as your client.
http://blog.philippheckel.com/2013/07/01/how-to-use-mitmproxy-to-read-and-modify-https-traffic-of-your-phone/

How to implement post method for this http post request ?

Hi this is my HTTP Post Request Method in Android client.i don't know how to implement the #POST method in the Restful web server.
public class AndroidHTTPRequestsActivity extends Activity
{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Creating HTTP client
HttpClient httpClient = new DefaultHttpClient();
// Creating HTTP Post
HttpPost httpPost = new HttpPost(
"http://localhost:8080/GPS_Taxi_Tracker_Web_Server/resources/rest.android.taxi.androidclientlocation/Login");
// Building post parameters
// key and value pair
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("email", "user#gmail.com"));
nameValuePair.add(new BasicNameValuePair("message",
"Hi, trying Android HTTP post!"));
// Url Encoding the POST parameters
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
// Making HTTP Request
try {
HttpResponse response = httpClient.execute(httpPost);
// writing response to log
Log.d("Http Response:", response.toString());
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
}
what is the implementation for the post method in the java restful web service , this is my code for the Rest sever what is wrong ?
#POST
#Path("{Login}")
#Consumes({"application/xml"})
public void Add(#PathParam("email") String email,AndroidClientLocation entity) {
entity.setEmail(email);
super.create(entity);
}
Multiple questions..
What are you using as container on server side
What is your base url mapping. Your API method's path being Login, how do are you routing the remaining part of the URL (/resources/rest.android.taxi.androidclientlocation) to the API.
The API consumes application/xml but the client code is not sending/setting Content-Type as application/xml, is it taken care by the client?
When you run the request from client what is the response (HTTP Error) that you get.
Where is your REST server running (Internal or External).
Answers to the question might clarify the request a bit more.
http://developer.android.com/tools/devices/emulator.html#networkaddresses
10.0.2.2 Special alias to your host loopback interface (i.e., 127.0.0.1 on your development machine)
http://localhost:8080/.
as per link & link2
Send a request to localhost' means to send it to the local machine. In your case that would be the Android device. You want to send the request to your desktop machine, which is a remote host. The problem is that the Appengine dev_sever by default only binds to the local address, so it can't be accessed remotely (i.e., from your Android device). You need to pass the --address option to make accessible from the outside. Check your computer's IP and pass it as the address. Something like:
dev_appserver.cmd --address=192.168.2.220

How can I capture a response sent from android to Django server using views.py?

I am new to the client-server side programming so my question might be basic.
Basically, I am trying to send data in JSON format from android to a Django server. The code for sending the data is the following:
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost:8000/androidweb/edit/");
JSONObject j = new JSONObject();
try {
j.put("name", "cdfe");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
nameValuePairs.add(new BasicNameValuePair("year", j.toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
}catch(Exception e) {
//catch the exception and print it
}
So my intention is to basically call the url mentioned in code. I added the url to Django urls.py so I can use the views.py class to store the JSON data I entered above in a sqlite database table, which contains only one field called "name". However, I don't know if my approach is right. Most code samples I have seen pass the data to a php file, so I was wondering if it is possible to do it through a python class, views.py?
If it is possible, can you please give me a code sample to be implemented in "views.py" of how to capture JSON data sent from the above code and store it in a table with a "name" field?
Thanks!
Data sent via POST is available via request.POST. Try examining request.POST['year'].

Categories

Resources