Cant Post data form android to php api - php

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

Related

how to make php login with android

The most confusing question today for all beginners is that how can we make login to user using my sql and php because we find many commands being deprecated. Can somebody explain best way to make a login either be its basicnamevaluepair or httppost or what ever. It will help everybody.
But i tried but didnot work like this
<?php
require "myfile.php";
$username=$_POST['username'];
$userpass=$_POST['password'];
echo 'username is '.$username;
echo 'password is '.$userpass;
$mysql_qry="Select * from employeedata where username like '$username' and password like '$userpass'";
$result=mysqli_query($conn,$mysql_qry);
if(mysqli_num_rows($result)>0)
{echo 'Login Success';
}
else{
echo 'Not success!';
}
?>
Here is myfile.php
<?php
$db_name="employee";
$mysql_username="root";
$mysql_password="";
$server_name="localhost";
$conn=mysqli_connect($server_name,$mysql_username,$mysql_password,$db_name);
if($conn)
{
echo 'Success!';
}
else{
echo 'Not success!';
}
?>
For android i used
URL url = new URL(myurl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
OutputStream o = connection.getOutputStream();
InputStream i = connection.getInputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(o, "UTF-8"));
Log.v("adsluser",email);
String postData = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(email, "UTF-8") + "&" +
URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
writer.write(postData);
// writer.flush();
// writer.close();
// o.close();
backresult = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(i, "iso-8859-1"));
String line;
while ((line = reader.readLine()) != null) {
backresult += line;
}
return backresult;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The error i got here is that data didnot get posted in that page. If i set default value and try it is success. Also it is success from browser too.
The error I find here is that you are reading InputStream after opening OutputStream but before posting your data.
Post your data and then only read InputStream because input stream is only expected received after you post data.
Try this
URL url = new URL(myurl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
OutputStream o = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(o, "UTF-8"));
Log.v("adsluser",email);
String postData = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(email, "UTF-8") + "&" +
URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
writer.write(postData);
writer.flush();
writer.close();
o.close();
backresult = "";
InputStream i = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(i, "iso-8859-1"));
String line;
while ((line = reader.readLine()) != null) {
backresult += line;
}
return backresult;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if the goal is simply to do a login, I would suggest leave all of this and go use firebase. Here is the link:
Link to Firebase
It is an amazing tool complete with a database, auth, and much more. I think it is the easiest way to get up and running.

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/

how to solve Java.Io.IoException in android

I'm trying to call php web service using post method and parameters, but im getting exception at OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); this line, i have noticed by debugging, i have search for this error but not getting any proper solutions, can anyone help me to solve this error? thanks in advance.
String data = URLEncoder.encode("name", "UTF-8")
+ "=" + URLEncoder.encode("wsd", "UTF-8");
data += "&" + URLEncoder.encode("email", "UTF-8") + "="
+ URLEncoder.encode("asd", "UTF-8");
data += "&" + URLEncoder.encode("user", "UTF-8")
+ "=" + URLEncoder.encode("asd", "UTF-8");
data += "&" + URLEncoder.encode("pass", "UTF-8")
+ "=" + URLEncoder.encode("sad", "UTF-8");
String text = "";
BufferedReader reader=null;
try
{
// Defined URL where to send data
URL url = new URL("http://androidexample.com/media/webservice/httppost.php");
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
}
text = sb.toString();
}
catch(Exception ex)
{
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
// Show response on activity
//content.setText( text );
return text;
}
On sending parameters, try this:
OutputStream output = new BufferedOutputStream(urlConnection.getOutputStream());
output.write(param.getBytes());
output.flush();
output.close();

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

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