sending values from android to php without namepair value - php

I want to send data from android to php.Am using android api 23 and from android's developers site a got to know that namepairvalue is deprecated from api 22 and above. I referred to one of the post here in stackoverflow and got the below code. but still it doesn't work.
My problem is that am sending a value(ID) to php code and based on that value fetching the records from database. Now if i fetch data without using this value it works fine, but i am unable to send the id value to php code.
i am unable to find whats wrong in this code or may be my fault is editing the code. It would be great if someone helps me to understand it clearly .
Thank you in advance.
Here is the code snippet that i have tried.
Android Code:
String sid = staffid.toString(); // this sid is passed as intent from another activity and passing it to below link.
Log.d("SID :", "" + sid);
try {
URL url = null;
url = new URL("http://usplhubli.96.lt/hrm/hrm_app/individual_view_staff.php");
Log.d("url to display :", "" + url.toString());
HttpURLConnection conn = null;
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(CONNECTION_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
// Log.d("os to display :", "" + os.toString());
Uri.Builder builder = new Uri.Builder().appendQueryParameter("sid", sid);
Log.d("builder to display :", "" + builder.toString());
String query = builder.build().getEncodedQuery();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
Log.d("writer display :", "" + writer.toString());
writer.write(query);
writer.flush();
writer.close();
os.close();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (ProtocolException e2) {
e2.printStackTrace();
} catch (IOException e3) {
e3.printStackTrace();
}
return null;
}
I have this code in doInBackground(String... params) of AsyncTask
based on this sid value i have to get the data from database and display it in android activity.
Here is the PHP code that i have tried
PHP Code:
$response=array();
$sid=$_POST["sid"]; // this is the POST data that am send from android
//$sid="4"; // this is the static value that i have tried and its working
print_r($sid);
include 'dbconfig.php';
$imagePath='http://www.usplhubli.96.lt/hrm';
$query=mysqli_query($conn,"select * from hrm_staff where sid='$sid'");
if(mysqli_num_rows($query) >0) {
$response["hrm_staff"] = array();
while ($row = mysqli_fetch_array($query)) {
$recp = array();
$recp["sid"]=$row["sid"];
$fullName=$row['fname']."".$row['mname']."".$row['lname'];
$recp["name"]= $fullName;
$recp["address"]=$row['address'];
$recp['city']=$row['city'];
$recp["design"]=$row['did'];
$recp["contact"]=$row['mobile'];
$recp["email"]=$row['email'];
$recp['qualification']=$row['quali'];
$recp["dateofjoining"]=$row['doj'];
$ppic1=$row['ppic'];
$ppic1;
$ppic21=$imagePath."/".trim($ppic1);
$recp["ppic"]= $ppic21;
array_push($response["hrm_staff"], $recp);
}
$response["success"] = 1;
$response["message"]="display records";
echo json_encode($response);
}
else
{
$response["success"] = 0;
$response["message"] = "No products found";
echo json_encode($response);
}
Please suggest. Thank you.

use these lines of code for using HttpURLConnection
For sending the request parameter are as:-
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("phone", number)
.appendQueryParameter("password", password)
.appendQueryParameter("device_login",value);
And for the getting the request parameter in the post method of connectionUrl are as follow:-
URL url = new URL(myurl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(30000);
urlConnection.setConnectTimeout(30000); ;
String query = builder.build().getEncodedQuery();
System.out.println("REQUEST PARAMETERS ARE===" + query);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.connect();
//Send request
DataOutputStream wr = new DataOutputStream (
urlConnection.getOutputStream ());
wr.writeBytes (query);
wr.flush ();
wr.close ();
//Get Response
InputStream isNew = urlConnection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(isNew));
String line;
response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
}
rd.close();
System.out.println("Final response===="+response);

There might be more than one issue but a big one is you never send the request, all you are doing is creating the request and setting up the parameters
you need to do a
conn.connect();
or
conn.getInputStream();
or any number of things you can do to send the request and get the information you require
AFTER you write your params

Related

Unable to fetch data from $_POST variable in PHP to Android Studio

I want to fetch the content of $_POST variable from a PHP hosted file into Android app. I have tried using Jsoup and Volley libraries to do this but they were not producing the expected result. Later, found out that echo ("anyString"); is being fetched to android but echo($_POST["orderId"]); is not being fetched even though it gets printed in web page. Is there any way of solving this issue?
This is the PHP code:
<?php
$secretkey = "7457645673urgjnjkf784jyj66545y";
$orderId = $_POST["orderId"];
$orderAmount = $_POST["orderAmount"];
$referenceId = $_POST["referenceId"];
$txStatus = $_POST["txStatus"];
$paymentMode = $_POST["paymentMode"];
$txMsg = $_POST["txMsg"];
$txTime = $_POST["txTime"];
$signature = $_POST["signature"];
$data = $orderId.$orderAmount.$referenceId.$txStatus.$paymentMode.$txMsg.$txTime;
$hash_hmac = hash_hmac('sha256', $data, $secretkey, true) ;
$computedSignature = base64_encode($hash_hmac);
if ($signature == $computedSignature) {
echo json_encode($_POST);
}
?>
The java code in Android:
URL link = new URL("https://sample.php");
HttpURLConnection conn;
conn = (HttpURLConnection) link.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("result", result.toString());
}
}catch (Exception e){
Log.d("result", e.toString());
}

php is not receiving data from android through httpUrlConnection

I am sending user email from Android app to PHP using HttpUrlConnection but PHP is not receiving Any data from App. This type of questions have already been asked but their solution do not worked for me. My Android Coding is
URL server_url = new URL("http://www.myURL.com/Jobs/login.php");
HttpURLConnection urlc = (HttpURLConnection) server_url.openConnection();
urlc.setDoOutput(true);
urlc.setDoInput(true);
urlc.setRequestMethod("POST");
urlc.setRequestProperty("Content-Language", "en-US");
urlc.setRequestProperty("Accept-Encoding", "identity");
urlc.connect();
HashMap<String, String> param = new HashMap<>();
param.put("email", mEmail);
DataOutputStream os = new DataOutputStream(urlc.getOutputStream());
os.writeBytes(URLEncoder.encode(mEmail, "UTF-8"));
os.flush();
os.close();
and My php code is:
<?php
$user_email=$_POST['email'];
echo "Email is $user_email";
?>
but when running this php on browser, it is echoing "Email is" as it is not receiving any data from android. Please Help
My php code contains only these two lines. Am I missing something in php coding?
You're not sending the paramater at all. You need to structure the request much better aswell since it's clear you're getting confused.
URL server_url = new URL("http://www.myURL.com/Jobs/login.php");
HttpURLConnection urlc = (HttpURLConnection) server_url.openConnection();
//header stuff
urlc.setRequestMethod("POST");
urlc.setRequestProperty("Content-Language", "en-US");
urlc.setRequestProperty("Accept-Encoding", "identity");
//params
String urlParameters = "email="+mEmail;
//send post
urlc.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(urlc.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
//read result
BufferedReader in = new BufferedReader(
new InputStreamReader(urlc.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString()
);
After so many solutions and discussion finally i got the solution..can not say solution but an alternative approach and it is " volley" library...i used it..and finally php receives the data....

Login with php in android

Hi I am new to android and I am trying to connect android to MySQL with php. I want to create a login system where only admin can login.
Below is my code
#Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
Boolean s = true;
String link = "http://localhost/eKos/login.php";
try{
URL url = new URL(link);
String data = URLEncoder.encode("username", "UTF-8") + "=" +
URLEncoder.encode(mUsername, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") + "=" +
URLEncoder.encode(mPassword, "UTF-8");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null) {
sb.append(line);
break;
}
if (sb.toString() != "Login Successful"){
s = false;
}
} catch (Exception e){
System.out.print("Exception: " + e.getMessage());
}
return s;
}
However, it seems like variable s is not modified at all inside the try block since this function always returns true.
Does anyone know how to fix this?
Thank you
try this:
if (!(sb.toString()).equals("Login Successful")){
s = false;
}
} catch (Exception e){
System.out.print("Exception: " + e.getMessage());
s = false;
}
return s;
Also print your server response whether it has Login Successful string in it..
and check if any exception is thrown
Are you using volley?
There is a great tutorial for this : https://www.youtube.com/watch?v=QxffHgiJ64M&list=PLe60o7ed8E-TztoF2K3y4VdDgT6APZ0ka
Why don't you Use "retrofit2" library?! it's far better, faster and easier than AsyncTask or Volly and it doesn't have the complexity of two mentioned libraries. You can use the links blow for more informarion:
https://square.github.io/retrofit/
And
http://www.androidhive.info/2016/05/android-working-with-retrofit-http-library/

Use of $_POST when php file is called by android app

I'm trying to upload some data in the database with an android app. Until now everything was working fine, but now I need to add another column, so I modified the code and now it looks like the data sent by the phone is not readable by my php files. The important part of the code of my app is the following:
private static void post(String endpoint, Map<String, String> params)
throws IOException {
URL url;
try {
url = new URL(endpoint);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("invalid url: " + endpoint);
}
StringBuilder bodyBuilder = new StringBuilder();
Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
// constructs the POST body using the parameters
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
bodyBuilder.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
bodyBuilder.append('&');
}
}
String body = bodyBuilder.toString();
Log.v(TAG, "Posting '" + body + "' to " + url);
byte[] bytes = body.getBytes();
HttpURLConnection conn = null;
try {
Log.e("URL", "> " + url);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
//conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
// post the request
OutputStream out = conn.getOutputStream();
Log.v(TAG, "Has posted" + bytes);
out.write(bytes);
out.close();
// handle the response
int status = conn.getResponseCode();
if (status != 200) {
Log.v(TAG, "Post Failed");
throw new IOException("Post failed with error code " + status);
}
} finally {
if (conn != null) {
conn.disconnect();
}
}
On the Logcat it looks like the app has been able to post the code effectively in byte format:
V/Alvaro Lloret GCM﹕ Posting email=llor&name=hola&arduinoweb=jaj&regId=APA' to http://youdomotics.com/mysecurity1/register.php
E/URL﹕ > http://website.com/mysecurity1/register.php
V/RenderScript﹕ Application requested CPU execution
V/RenderScript﹕ 0xaec16400 Launching thread(s), CPUs 4
V/Alvaro Lloret GCM﹕ Has posted[B#16d173b0
V/GCMRegistrar﹕ Setting registeredOnServer status as true until 2015-09-11 20:21:30.364
V/GCMBaseIntentService﹕ Releasing wakelock
Then, the code to receive the post with php is the following:
<?php
// response json
$json = array();
if (isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["regId"]) ) {
require("config.php");
$con = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$name = $_POST["name"];
$email = $_POST["email"];
$arduinoweb = $_POST["arduinoweb"];
$gcm_regid = $_POST["regId"]; // GCM Registration ID
include_once './gcm.php';
$query = "INSERT INTO gcm_users_new(name, email, gcm_regid, arduinoweb, created_at) VALUES('$name', '$email', '$gcm_regid', '$arduinoweb', NOW())";
mysqli_query($con, $query);
} else {
// user details missing
}
?>
This code worked perfectly without the new parameter arduinoweb, but since I added this other parameter, the row is not added into the database. If I comment the condition if (isset...), then the file adds a row in the table, but it's empty...
Any ideas?
Thank you!!
Okay I solved!
The perfect answer is here
I just had to change to www. when I called the URL and that made it work!

php could not receive data sent by Android using HttpURLConnection

I'm try to send some data back from Android to server(database) using OutputStreamWriter but I cant see any result in the database and Logcat is fine. I tried the solutions posted on stackoverflow but no luck. Here are my codes:-
private class sentFeedback extends AsyncTask<String,Void,String>{
#Override
protected String doInBackground(String... params) {
if(isNetworkAvailable()){
try{
URL feedback = new URL("http:.../setFeedback.php");
HttpURLConnection conn = (HttpURLConnection) feedback.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
String data = getData(params);
wr.write(data);
wr.flush();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else{
return "No internet connection";
}
return null;
}
public String getData(String... params) throws UnsupportedEncodingException {
String data = "id" + "=" + URLEncoder.encode(params[0], "UTF-8");
data += "&" + "rating" + "=" + URLEncoder.encode(params[1], "UTF-8");
data += "&" + "message" + "=" + URLEncoder.encode(params[2], "UTF-8");
return data;
}
}
php code:-
$id = $_POST['id'];
$rating = (double)$_POST['rating'];
$message = $_POST['message'];
$feedbackQuery = "INSERT INTO feedback(message, id, rating) VALUES ('$message', '$id', '$rating')";
$feedbackQueryResult = $mysqli->query($feedbackQuery);
$mysqli->close();
Currently I'm using a free 000webhost account. Is that the reason which I can send the data back?
Thanks in advance!!
in php file Replace the your tablenName with your dbName.tableName in Query string for example if db name is mydb
$feedbackQuery = "INSERT INTO mydb.feedback(message, id, rating) VALUES ('$message', '$id', '$rating')";
and test again,in one project my problem solve with this

Categories