php could not receive data sent by Android using HttpURLConnection - php

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

Related

Cant Post data form android to php api

I have created an API using PHP and MYSQL and now i want to get data in Android.
My API works fine if i pass static data to it and run in browser but when i try to post data to android it throws an exception. I want to post username password for mysql database and a word through which it will return the word and definition in JSON format. Again as a I mentioned it works fine when i add static data in my php script but not working when posting through android. Here's what i've done so far
PHP
<?php
header('Content-type: application/json');
$username=urlencode($_POST["username"]);
$pass=urlencode($_POST["pass"]);
$connect = mysqli_connect('pakscrabble.ipowermysql.com', $username, $pass,'csw19');
if (!$connect) {
die('Could not connect: ' . mysql_error());
}
$w=urlencode($_POST["wordtosearch"]);
$q="select * from words where word='".$w."' ";
$query=mysqli_query($connect,$q);
$dict_data = array();
while($row=mysqli_fetch_array($query))
{ $dict_data[] = array(
'word' => $row[0],
'def' => $row[1] );
}
echo "<pre>";
print_r(json_encode($dict_data));
echo "</pre>";
?>
Android
String urlString = params[0]; // URL to call
String username = params[1];
String pass=params[2];
String wordtosearch=params[3];
OutputStream out = null;
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
out = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
String data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("pass", "UTF-8") + "="
+ URLEncoder.encode(pass, "UTF-8");
data += "&" + URLEncoder.encode("wordtosearch", "UTF-8")
+ "=" + URLEncoder.encode(wordtosearch, "UTF-8");
writer.write(data);
writer.flush();
writer.close();
out.close();
urlConnection.connect();
JSONObject responseJSON = new JSONObject();
Toast.makeText(c, String.valueOf(responseJSON.getString("def")), Toast.LENGTH_SHORT).show();
String loginMessage = responseJSON.getString("loginMessage");
String userName = responseJSON.getString("user");
} catch (Exception e) {
Toast.makeText(c, e.getMessage(), Toast.LENGTH_SHORT).show();
return "something happened";
}
return "Hello World!";
Never reaches the Hello World part and throws an exception

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/

sending values from android to php without namepair value

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

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!

Post multiple data from Android to PHP web service

So far I can send one set of data from Android to PHP web service. I'm hoping to send an array, and have a for loop in the web service. Is that possible? Is that a good solution? In this project, I'm trying to sync SQLite with MySQL.
Here's my code
String username, userid;
username = "Kate";
userid = "3";
String data = "";
try {
data = URLEncoder.encode("username", "UTF-8") + "="
+ URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("userid", "UTF-8") + "="
+ URLEncoder.encode(userid, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String text = "";
BufferedReader reader = null;
try {
URL url = new URL(
address);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(
conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
text = sb.toString();
} catch (Exception ex) {
} finally {
try {
reader.close();
} catch (Exception ex) { }
}
And this
<?php
include '../inc/connect.php';
include '../inc/class/mysql.class.php';
$name = urldecode($_POST['username']);
$user = urldecode($_POST['userid']);
print " ==== POST DATA =====
Name : $name
Email : $email
User : $user
Pass : $pass";
$ins = mysql_query("INSERT INTO users (UserName, FullName) VALUES ('$name','$user')") or die(mysql_error());
if ($ins) {
echo json_encode(array("result"=>"success","result_txt"=>"Branch sucessfully added."));
exit();
}
?>
You could send the input as JSON and then get PHP to decode it.
So you'd encode all your data in the android app and send it as one big encoded string, possibly using URI encoding or Base64, then in the PHP do:
$data = json_decode($_POST['data']);
If you use base64 then you'd do:
$data = json_decode(base64_decode($_POST['data']));
If you just send it as one string
$data = json_decode(urldecode($_POST['data']));

Categories