I have created an app that takes the current location of the phone and then should send it to an apache web server. I'm using a php file on the server to receive the data and then write it to an HTML file. The domain works fine, and it properly displays the html file that I have on the web server, but the php file does not write the data to the html file and I'm not sure why.
Here is the code for sending the data
if (currentLocation == null) {
return;
}
else {
//Creating strings for the latitude and longitude values of our current location
String latitude = new String(" " + (Math.round(currentLocation.getLatitude()*10000000))/10000000);
String longitude = new String(" " + (Math.round(currentLocation.getLatitude()*10000000))/10000000);
// Creating an http client and http post object in order to interact with server
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://findmylocation.chandlermatz.com/");
try {
//Creating identifier and value pairs for the information we want to send to server
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("Latitude", latitude));
nameValuePairs.add(new BasicNameValuePair("Longitude", longitude));
//Sending data to server via http client
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
}
catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
And here is my php code
<?php
// get the "message" variable from the post request
// this is the data coming from the Android app
$latitude = $_POST["Latitude"];
$longitude = $_POST["Longitude"];
// specify the file where we will save the contents of the variable message
$filename="index.html";
// write (append) the data to the file
file_put_contents($filename,date('m/d/Y H:i:s') . "      " . $latitude . "   " . $longitude . "<br />",FILE_APPEND);
?>
Any help is appreciated!
Related
I use nodejs as server and java(android) as client,i succes send data through post from android to node. but my problem when android send the data (string) consist of space and new line (enter) its received on node but the character was change,
for example,i send this string from android
Hello
I learn android
the string send to node and received,but i get this in node
Hello%0AI+learn+android
I use this code for send string to node in android.
public void btnOnClick(){
String text= URLEncoder.encode(editText.getText().toString(), "utf-8"); //I get from editText and convert to utf-8
sendToNode(text);
}
public void sendToNode(String text){
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://myDomain.com:8888/");
UrlEncodedFormEntity form;
try {
Log.i("kirim ke node isitextAsli ",text);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("datanah",text));
form=new UrlEncodedFormEntity(nameValuePairs,"UTF-8");
httppost.setEntity(form);
HttpResponse response = httpclient.execute(httppost);
Log.i("HTTP Post", "Response from server node = " + response.getStatusLine().getReasonPhrase() + " Code = " + response.getStatusLine().getStatusCode());
} catch (ClientProtocolException e) {
Log.e("HTTP Post", "Protocol error = " + e.toString());
} catch (IOException e) {
Log.e("HTTP Post", "IO error = " + e.toString());
}
}
and I use this code for receive string in node
req.addListener('data', function(chunk) { data += chunk; });
req.addListener('end', function() {
console.log("from android :"+data); //result of data is Hello%0AI+learn+android
});
How i solve my problem?
please help,Thanks.
The string is URL-encoded, as you explicitly asked for in your code (and need for a regular POST). Decode it on the server.
To decode it on the server side, do:
var querystring = require('querystring');
querystring.unescape(data.replace(/\+/g, " "));
The following is the sample of encoding and decoding, YOU WANT TO DECODE IN THE SERVER PART
String encoded;
try {
encoded = URLEncoder.encode(input, "UTF-8");
System.out.println("URL-encoded by client with UTF-8: " + encoded);
String incorrectDecoded = URLDecoder.decode(encoded, "ISO-8859-1");
System.out.println("Then URL-decoded by server with ISO-8859-1: " + incorrectDecoded);
String correctDecoded = URLDecoder.decode(encoded, "UTF-8");
System.out.println("Server should URL-decode with UTF-8: " + correctDecoded);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I'm trying to program a Login-System for Android (in Eclipse) and have to get the data from an external MySQL-DB.
Source I took the code for it: Connecting to MySQL Database
The Website I'm trying to fetch the data from is here.(I know there are some safety issues, blabla, this is not my problem right now^^)
The Problem I have, is when I try to run the Application, The Error "No Password found".
This Error is catched within this Code:
ArrayList<String> passwort = new ArrayList<String>();
ArrayList<String> benutzer = new ArrayList<String>();
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
passwort.add(json_data.getString("pw"));
benutzer.add(json_data.getString("benutzer"));
}
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("arrayBenutzerExtra", benutzer);
intent.putExtra("arrayPasswortExtra", passwort);
startActivity(intent);
}
catch(JSONException e1){
Toast.makeText(getBaseContext(), "No Password found" ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
As addition, here is the code where I connect with the website, but it doesn't seem to be the problem, though I don't get an error message about that!
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://winklermarkus.at/appconnection.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
The Code of the .php file is here:
$sql_pw = "SELECT ". "Passwort ". "FROM ". "benutzerdaten ";
$result_pw = mysql_query ($sql_pw);
$data_pw = mysql_fetch_array ($result_pw);
$pw = $data_pw["Passwort"];
$sql_benutzer = "SELECT ". "Email ". "FROM ". "benutzerdaten ";
$result_benutzer = mysql_query ($sql_benutzer);
$data_benutzer = mysql_fetch_array ($result_benutzer);
$benutzer = $data_benutzer["Email"];
print(json_encode($pw));
print(json_encode($benutzer));
mysql_close();
?>
as Perception mentioned, I don't get valid JSON output, could this possibly be in relation with me, trying to transmit 2 strings at once?
Your PHP code is not doing what you think it's doing. I cannot recommend a fix to it as you've created a significant security hole.
As an alternative strategy, instead of sending all the passwords and all the emails to the client (in an unassociated fashion no less), send the clients hashed password and email to the service (over SSL). Then on the service side query if you have the combination of email/pass in the database. If you do return login success, otherwise return login failed.
I've researched all the internet and found articles on How to use http post from android to php server. I'm not looking for examples of how to pass data from android to website. I'm looking for reasons why POST variable is always NULL in PHP. Is there some setting I need to check for on PHP (I've checked the output buffering, max post, etc) or import a class for the HTTP POST to work correctly for POST variable.
The below codes basically insert values into mysql database. Because the POST variables are blank, it's inserting blank rows. This verified that it's connecting to my server/database, but the POST values are not being passed. Any idea? =)
Below are the codes:
//Java Code-------------------------------------------------
public static void executeHttpGet(Context context, String urlName){
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
String postURL = G.GetUrl(urlName);
HttpPost httpPost = new HttpPost(postURL);
httpPost.setHeader("Accept", "text/html,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try {
nameValuePairs.add(new BasicNameValuePair("value1", "My Name"));
nameValuePairs.add(new BasicNameValuePair("value2", "My Address"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httpPost);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
//PHP code ----------------------------------------------------
connectMySQL();
mysql_query("
INSERT INTO myhome(myname,myaddress,createdate)
VALUES('{$_POST['value1']}','{$_POST['value2']}',NOW())
;")
or die(mysql_error());
Can you try to print $_POST['value1'] and $_POST['value2'] before using them in your SQL and see what they print?
For the sake of simplicity I would suggest you rewrite your PHP code:
connectMySQL();
$value1 = trim($_POST['value1']);
$value2 = trim($_POST['value2']);
if ($value1 != "" && $value2 != "") {
mysql_query("
INSERT INTO myhome(myname,myaddress,createdate)
VALUES('".$value1."','".$value2."',NOW())
;")
}
Also, once you have verified it is working, I highly recommend you read about SQL injection attacks and try to use bind variables or parameterized queries instead of directly using request parameter values in your SQL statement.
I have created an android application using java, php(backend) and mysql(database). I have placed my backend php code and the database on Linux hosting server. My problem is that I can only read the data from the database, i.e., my application can fetch the data from the server, but it couldn't make any changes to the fetched data and also I get errors when I run using the server, but when I placed the database and code in local system it works perfectly on the localhost, but when placed in server it can only read the data but not insert, update or delete the data. I have already given full privileges to the database in the server. Can anyone please help me regarding this aspect?
I think the server doesn't accept requests from outsider like mobile. So my question is
what do we need to do such that the server accepts requests from mobile side?
PS: I have given full privileges to the database in server and also I have added Internet permission in the android manifest file.
#Lie Ryan: As per your request, here is my code to connect to server:
protected List<List<String>> callWebServer(String queryString, String statement){
List<List<String>> stringList = null;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("query", queryString));
nameValuePairs.add(new BasicNameValuePair("statement", statement));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(WEB_SERVICE_URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost,responseHandler);
JSONObject json = new JSONObject(responseBody);
if(statement.equals(DB_SELECT_STATEMENT) || statement.equals(DB_INSERT_STATEMENT)){
List<String> queryStrings = null;
// parsing query
if(statement.equals(DB_SELECT_STATEMENT)){
queryStrings = splitQuery(queryString);
JSONArray jArray = json.getJSONArray("output");
if(jArray.length() > 0)
stringList = new ArrayList<List<String>>();
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
String rowData = json_data.getString("rowData");
if(rowData.equals("nothing")){
// Toast.makeText(getBaseContext(), "No record found", Toast.LENGTH_LONG).show();
}else{
JSONObject getClassNameObject = new JSONObject(rowData);
List<String> tempStringList = new ArrayList<String>();
for(String valueStr:queryStrings){
if(valueStr.contains(".")) valueStr = valueStr.split("\\.")[1];
tempStringList.add(getClassNameObject.getString(valueStr));
}
stringList.add(tempStringList);
}
}
}else{
JSONArray jArray = json.getJSONArray("output");
stringList = new ArrayList<List<String>>();
JSONObject json_data = jArray.getJSONObject(0);
stringList.add(getList("mn", json_data.getString("rowData")));
}
}
//Toast.makeText(getBaseContext(), "Event Added Successfully", Toast.LENGTH_LONG).show();
}catch(ArrayIndexOutOfBoundsException e){
}catch(Exception e){
Log.e("log_tag", "Error in http connection:"+e.toString());
}
and the php code to handle the request is:
<?php
include "connect.php";
if($_POST["statement"] == "select"){
$booleanRow = true;
// for select statements
$db_output = mysql_query($_POST["query"]));
while($row=mysql_fetch_array($db_output, MYSQL_ASSOC)){
$output[] = array('rowData'=>$row);
$booleanRow = false;
}
if($booleanRow){
$row = "nothing";
$output[] = array('rowData'=>$row);
}
print(json_encode(array('output'=>$output)));
}else{
// for insert, update and delete
mysql_query($_POST["query"]);
$row = mysql_insert_id();
$output[] = array('rowData'=>$row);
print(json_encode(array('output'=>$output)));
}
mysql_close($link);
?>
Thanks in Advance.
To allow applications to open network sockets you need to set the 'android.permission.INTERNET' permission in your android manifest file (AndroidManifest.xml):
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
For a list of more permissions see the Manifest.Permission class.
I am trying to implement a class that gets data from mysql via my web service. I have previously used a http post to get information from a table but this time I intend a user to input a string into an editText, press search and the textview to display the query.For example, Imagine there are two columns of the mysql table: Firstname and surname; I would like to be able to get the surname by searching the Firstname (Entering the Firstname into the EditText and displaying the surname of that person).I have developed the PHP script but is it possible to use the HTTP get method based on an input string? how? I've only seen tutorials directing straight to the php link
This is a example how you could do it by using NameValuePairs which you can pass to the php file using a post request.
private void sendData(ArrayList<NameValuePair> data)
{
// 1) Connect via HTTP. 2) Encode data. 3) Send data.
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://www.blah.com/AddAccelerationData.php");
httppost.setEntity(new UrlEncodedFormEntity(data));
HttpResponse response = httpclient.execute(httppost);
Log.i("postData", response.getStatusLine().toString());
//Could do something better with response.
}
catch(Exception e)
{
Log.e("log_tag", "Error: "+e.toString());
}
}
Now lets say you want to use this method to pass info(i.e. your parameter to the php file.
//Add data to be send.
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("parameter",editTextValue));
this.sendData(nameValuePairs);
Now on the php side of things you can then get this parameter value by calling:
//Retrieve the data.
$parameter = $_POST['parameter'];
//Now call on your query or function or w/e it is using this parameter.
To use GET, simply encode the values into your URL, e.g.
String url = "http://myserver.net/script.php?first=" + URLEncoder.encode(first) +
"&last=" + URLEncoder.encode(last);
And then use an HttpGet object with your HttpClient:
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(new HttpGet(url));
Processing the response is then the same as if you had posted it.