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']));
Related
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());
}
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
I m trying to send a Json Post request using my Android Application.
But something weird happens.
Here is my Android Code:
try {
URL url = new URL(BASE_URL + params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type","application/json");
connection.connect();
//JSonObject
JSONObject json = new JSONObject();
for(int i = 0 ; i < jsonValues.size(); i +=2){
json.put(jsonValues.get(i), jsonValues.get(i + 1));
}
jsonValues.clear();
DataOutputStream output = new DataOutputStream(connection.getOutputStream());
//String encoded= URLEncoder.encode(json.toString(),"UTF-8");
output.writeBytes(URLEncoder.encode(json.toString(),"UTF-8"));
output.flush();
output.close();
int HttpResult = connection.getResponseCode();
if(HttpResult ==HttpURLConnection.HTTP_OK){
BufferedReader br = new BufferedReader(new InputStreamReader(
connection.getInputStream(),"UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
String lineDecoded = URLDecoder.decode(line, "UTF-8");
sb.append(lineDecoded + "\n");
}
br.close();
System.out.println(""+sb.toString());
if(sb != null){
return sb.toString();
}else{
return null;
}
}else{
Log.d("ERRORRRRR",connection.getResponseMessage());
return connection.getResponseMessage();
}
} catch (MalformedURLException e) {
e.printStackTrace();
return e.toString();
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} catch (JSONException e) {
e.printStackTrace();
return e.toString();
}
My php code is this:
$content = file_get_contents("php://input");
if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0)
{
throw new Exception('Request method must be POST!');
}
//Make sure that the content type of the POST request has been set to
application/json
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if(strcasecmp($contentType, 'application/json') != 0){
throw new Exception('Content type must be: application/json');
}
//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));
//Attempt to decode the incoming RAW post data from JSON.
$decoded = json_decode($content, true);
echo($decoded);
exit;
The $decoded is null when I make a request using my Android application and using json_last_error() function I get JSON_ERROR_SYNTAX.
This is the raw content of the post request:
{"name":"test","identifier":"12345677"}
But I can't understand what is the problem. In fact when I try to use Advance Rest Client to simulate the same request it works perfectly as shown in the picture below.
I finally solved my Problem.. It seems to be the
URLEncoder.encode(json.toString(),"UTF-8");
In fact removing it and sending just output.writeBytes(json.toString());
Everything works perfectly
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/
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