how to send data from android to server - android

I'm exploring to scan ssid and rssi from android and I'm able to do it, but now i have want send the data to the server, so i explore i found below code
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://101.34.45.45/rawData");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("userId", "00-22-68-E8-EC-F1"));
nameValuePairs.add(new BasicNameValuePair("timestamp", "2010-07-01 11:11:11"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
textView.setText(response.toString());
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
but now i'm having problem when add multi wifi data, the format should as below
http://101.34.45.45/rawData?data={"userId":"guest1","timestamp":"2010-07-01 08:58:23","wifi":[{"ssid":"guest","rssi":"40"},{"ssid":"guest1","rssi":"80"}]},
so how can done for the wifi parameter, can anyone help, I'm still trying for few varieties,
thanks

I would recommend you to switch to JSON for sending data to the server. Google gson is easiest to use to send and parse JSON.
{"userId":"guest1","timestamp":"2010-07-01 08:58:23","wifi":[{"ssid":"guest","rssi":"40"},{"ssid":"guest1","rssi":"80"}]}
You should use a JSON object having a JSON array as one of its items. The JSON array in turn contains another json object.
If you are using Google GSON, you should build a class hierarchy for the same. Heres how you should do the same.
Class data{
String userId;
String timestamp;
Wifi wifi;
}
Class Wifi{
String ssid;
int rssi;
}
You can check here for a sample code on a similar problem on parsing json in android.
This may be useful too.

Related

How to create a web server using android studio?

I want to send some data collected by the app to the computer through internet. And secondly, apart from this, want to show live feed of the camera on the computer via internet.
I think making a web server will be a good option for the first requirement. But as I am new to android development, so please guide me.
For the live feed option, please suggest how this can be acheived.
Im not sure if this is good idea if you are new to android. Maybe start with something easier but if you do plan to do it any way.
To send data collected by the app you will have to send it to some kind of backend you will have to make it i suggest making it in PHP and saving the data in a Mysql database.
For the sending part you will probably want to do it in the background with a AsyncTask and it will look something like this :
public class Backend extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String server = "http://example.com/foo/bar"
String uid = params[0];
String name = params[1];
String email = params[2];
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(server+"NewUser.php");
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
nameValuePair.add(new BasicNameValuePair("uid", uid));
nameValuePair.add(new BasicNameValuePair("email", email));
nameValuePair.add(new BasicNameValuePair("name", name));
try {
// Probeer dat te zetten
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
// Execute
HttpResponse response = httpClient.execute(httpPost);
// Zet response om naar String
String responseBody = EntityUtils.toString(response.getEntity());
return responseBody;
} catch (ClientProtocolException e) {
e.printStackTrace();
return "0";
} catch (IOException e) {
e.printStackTrace();
return "0";
}
}
}
And you can execute this class like this:
new Backend().execute("1","maantje","email#example.com")
This will now POST uid, email, name to example.com/foo/bar/NewUser.php
So you will have to create that the data will be in $_POST['uid],$_POST['email'] and $_POST['name'].
Also don't forget the internet permissions in your manifest
<uses-permission android:name="android.permission.INTERNET" />
For the live feed option i have no experience with that but maybe this is a good place to start https://github.com/fyhertz/libstreaming
You are right. You need server which can handle your request from phone. Basically you need web-service which is called api. You can create those api by using java,node.js etc and you need database to store your data. For database purpose, you can use MongoDB or any other database.
Your api will handle POST request to hold the data from user request from the app. This is how, you can hold user data.
For live feed of the camera, I am not sure. Expecting to hear from some expert guys. Thanks and best of luck

Android Java SQL Connect

So i'm a web developer by trade but am making an app at the moment.
I've got a program on my PC which sends data from my PC to a database on my webhost.
What I'm after now, is to create an app that is able to download that data with a series of queries.
Are there any good resources around that would help me to develop some Java code, to connect to a server through my tablet when I'm out and about and download the information from my webhost when on a different wifi network?
Thanks chaps, any help is appreciated.
The way I handle it is that I just create a web page based on what I want to do. For example if I want to verify a login on an app I create a page that takes in a username and password.
On the device I just post the username and password values by using a HTTP post transaction.
Example:
public boolean LoginUser()
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("your URL comes here...");
try
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
DataCrypt crypt = new DataCrypt();
try
{
this.Cryptemail = crypt.bytesToHex(crypt.encrypt(this.Email));;
this.Cryptpass = crypt.bytesToHex(crypt.encrypt(this.Password));
}
catch (Exception e)
{
DebugLog.log(e.getMessage());
}
nameValuePairs.add(new BasicNameValuePair("Password", this.Cryptpass));
nameValuePairs.add(new BasicNameValuePair("Mail", this.Cryptemail));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
BasicHttpResponse response = (BasicHttpResponse) httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String response = EntityUtils.toString(entity);
return true;
}
catch (Exception e)
{
DebugLog.log(e.getMessage());
return false;
}
return false;
}
EDIT: So you can just make a page that takes in some parameters that you want to base your query on and return the result in some way (for example by XML).
Hope this helps you out! :)

How to send a JSON object over HttpClient Request with Android?

I want to send the JSON text {} to a web service and read the response. How can I do this from android? What are the steps such as creating request object, setting content headers, etc.
My code is here
public void postData(String result,JSONObject obj) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
String json=obj.toString();
try {
HttpPost httppost = new HttpPost(result.toString());
StringEntity se = new StringEntity(obj.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String temp = EntityUtils.toString(response.getEntity());
Log.i("tag", temp);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
what mistake i have done plz correct me because it shows me an bad request error
but when i do post in poster it shows me status as Successfull 200 ok
I do this with
httppost.setHeader("Content-type", "application/json");
Also, the new HttpPost() takes the web service URL as argument.
In the try catch loop, I did this:
HttpPost post = new HttpPost(
"https://www.placeyoururlhere.com");
post.setHeader(HTTP.CONTENT_TYPE,"application/json" );
List<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("json", json));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpClient client = new DefaultHttpClient();
HttpResponse resp = client.execute(post);
HttpEntity entity = resp.getEntity();
response = EntityUtils.toString(entity);
You can add your nameValurPairs according to how many fields you have.
Typically the JSON might become really huge, which I will then suggest gzipping it then sending, but if your JSON is fairly small and always the same size the above should work for you.
If it is a web service and not RestAPI call then, you can get the WSDL file from the server and use a SOAP Stub generator to do all the work of creating the Request objects and the networking code for you, for example WSClient++
If you wish to do it by yourself then things get a little tricky. Android doesn't come with SOAP library.
However, you can download 3rd party library here: http://code.google.com/p/ksoap2-android/
If you need help using it, you might find this thread helpful: How to call a .NET Webservice from Android using KSOAP2?
If its a REST-API Call like POST or GET to be more specific then its is very simple
Just pass a JSON Formatted String object in you function and use org.json package to parse the response string for you.
Hope this helps.

HTTP Post OK, how to display the response?

I'm trying to increase my knowledge to Android and trying to code a small app for my personal needs.
I'm trying to post data via the HTTP Post method on a test server.
The request is sent ok, but now, I'm trying to display the response, which is an HTML page with the dump of my request.
Here is an extract of my code, it is basically a few EditText fields, and button that sends the request.
The following code is the listener for that button.
validateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://posttestserver.com/post.php?dump&html&dir=mydir&status_code=200");
try {
// Gathering data
String value01 = nb01Spinner.getSelectedItem().toString();
String value02 = nb02EditText.getText().toString();
String value03 = nb03EditText.getText().toString();
String value04 = nb04EditText.getText().toString();
// Add data to value pairs
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(04);
nameValuePairs.add(new BasicNameValuePair("test01", value01));
nameValuePairs.add(new BasicNameValuePair("test02", value02)); //
nameValuePairs.add(new BasicNameValuePair("test03", value03));
nameValuePairs.add(new BasicNameValuePair("test04", value04));
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
}
I'm not sure if I need to create another Activity or not... I suppose I also have to create a webview aswell, but I'm a bit lost. For now the "raw" HTML would be fine, but afterwards I will need to parse the data, and extract only the strings I need.
So I would need help (an a good and simple example !)
Thank you.
String ret = EntityUtils.toString(response.getEntity());
Maybe this will help?
Very simple approach is Take textview the way you have taken button widget. and what ever response you got set in the textview. you will be able to see the response. else use the Log to log your response in the logcat.
This is how you get the Http response :
byte[] buffer = new byte[1024];
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://www.rpc.booom.com");
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("params","1"));
//.......
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse response = httpclient.execute(httppost);
Log.w("Response ","Status line : "+ response.getStatusLine().toString());
buffer = EntityUtils.toString(response.getEntity()).getBytes();
I am using:
Log.d("log_response", response.getStatusLine().toString());

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