I have android application that check if in DB exists already the phone number. but always it return "+" even there doesn't exists the phone number, this is my code:
URL url = new URL(URL_CHECK);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
String data = URLEncoder.encode("cphone", "UTF-8") + "=" + URLEncoder.encode(params[0], "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(IS, "UTF-8"));
String response = "";
String line ="";
while ((line = bufferedReader.readLine()) != null) {
response += line;
}
bufferedReader.close();
IS.close();
info = response;
return info;
The variable "info" always equals "+". This is my PHP Script:
<?php
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$dbname = "registers";
$con = new mysqli($servername, $username, $password, $dbname);
$user_name = $_POST["cphone"];
$sql_query = "select id from users where phone like '$user_name';";
$result = mysqli_query($con,$sql_query);
if(mysqli_num_rows($result) >0 )
{
$row = mysqli_fetch_assoc($result);
$name =$row["id"];
echo "$name";
}
else
{
echo "+";
}
?>
The php script work when instead of $_POST["cphone"] I write example "+37455001100".
The way you POST the value might be wrong. You can refer an answer at https://stackoverflow.com/a/2938787/2435238 on correctly sending parameters.
Related
I am trying to create my first android application that utilizes a REST api. My api is written in Node.JS and has already been tested using Postman, however, I am having trouble sending JSON data to my api.
#Override
protected String doInBackground(String... params) {
String data = "";
String urlName = params[0];
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection) new URL(urlName).openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes(params[1]);
wr.flush();
wr.close();
InputStream in = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(in);
int inputStreamData = inputStreamReader.read();
while (inputStreamData != -1) {
char current = (char) inputStreamData;
inputStreamData = inputStreamReader.read();
data += current;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
return data;
}
I always reach the line that declares and initializes my DataOutputSteam and doesn't execute the code. I am not even getting a log that my Virtual device has visited my server at all.
I have included in the manifest XML both of these already.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
Based on your logs, you're hitting a NetworkOnMainThreadException and that's preventing the network request from being executed (it's going into your catch block instead). This suggests you aren't calling your AsyncTask correctly - ensure that you're calling execute instead of calling doInBackground. See also here for more information on this general pattern.
Try this, it is for POST method that accept 2 parameter email and password.
Change it based on your requirement
URL url = new URL(Login_url);
HttpURLConnection conn = (HttpURLConnection) new URL(urlName).openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept" , "application/json");
conn.connect();
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("email", "Your_Email")
.appendQueryParameter("password","Your_Password");
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
code = conn.getResponseCode();
Log.e("Result", code + "");
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.e("Result",result.toString());
i asked this same question yesterday but i was not too clear about what i wanted the function to do, so i thought that i'd might give it another try!
i want to send data from a java program to a mysql server that i'm currently hosting via a local xampp server. Since this java class is will be used by a code written in android (also swift) it wont be possibe (atleast without a headache) to use a jdbc driver, therefor i'm trying to pass data to a php server with the help of java POST.
The problem is that literally nothing happens when i run the code. no errors, no data is being added to the sql, nothing is happening. So maybe a better programmer than be can have a look at my code and maybe see an issue that i currently can't!
Java code:
public static String main(String x, String y){
try{
String username = x;
String password = y;
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(username,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
// LÄSER FRÅN HEMSIDAN
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine()) != null){
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
}catch(Exception e){
e.printStackTrace();
}
return null;
}
PHP
<body>
<?php
$db_name = "smoothie";
$mysql_username = "root";
$mysql_password = "";
$server_name = "localhost";
$usr = $_POST["username"];
$pass = $_POST["password"];
$conn = mysql_connect($server_name,$mysql_username,$mysql_password,$db_name);
$query = "INSERT INTO members (username, password)
VALUES ('$usr','$pass')";
?>
I could really use some help here!! :)
I'm trying to check if a number exists in the database, but am unable to send forward the data from android to php.
Should the data be String, JSON or HashMap? How do I send it?
Java
try {
URL url = new URL("http://192.168.0.106/cei/tourist_home_activities.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setReadTimeout(15*1000);
conn.setConnectTimeout(15*1000);
conn.setRequestProperty( "Content-Type", "application/json" );
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
OutputStream os = conn.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
bufferedWriter.write(*Here is where I assume I input data*);
bufferedWriter.flush();
bufferedWriter.close();
os.close();
InputStream inputStream = conn.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String line = "";
while ((line = bufferedReader.readLine())!=null)
{
response+= line;
}
bufferedReader.close();
inputStream.close();
conn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
PHP
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
mysqli_select_db($conn,"discover_ilhabela");
$PIN=$_POST['pin'];
$result = mysqli_query($conn, "SELECT Name FROM `monitors` WHERE `PIN`='$PIN'");
/* if (mysql_num_rows($result)==1)
{
print("1");
}
else
{
print("0");
} */
print($PIN);
?>
I'm trying to check if there is any result to confirm that the number exists in the database, but first I'm just trying to return the string and it's returning as empty.
Your PHP endpoint expects $_POST['pin'] so you should send as plain text. Refer to this: How to add parameters to HttpURLConnection using POST
i'm devoloping an Android app. For the signin i need to send a database the data, but when i try to use $_POST array after the encode it seems be empty (i've tried to print the response, and i think this is my problem).
Here is the javacode inside my app:
private String register (String username, String password, String number) {
String reg_url = "myDomain/register.php";
try {
URL url = new URL(reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestProperty("Accept-Charset", "UTF-8");
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
String data = URLEncoder.encode("username", "UTF-8") + " = " + URLEncoder.encode(username, "UTF-8") + "&" +
URLEncoder.encode("password", "UTF-8") + " = " + URLEncoder.encode(password, "UTF-8") + "&" +
URLEncoder.encode("number", "UTF-8") + " = " + URLEncoder.encode(number, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS = httpURLConnection.getInputStream();
BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(IS,"iso-8859-1"));
String response = "";
String line;
while ((line = bufferedReader.readLine())!=null) response += line ;
Log.i("Response", response);
IS.close();
bufferedReader.close();
if (!response.toLowerCase().contains("fail"))
return Language.registered;
else
return Language.aProblemOccurred;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return Language.aProblemOccurred;
} catch (IOException e) {
e.printStackTrace();
return Language.aProblemOccurred;
}
}
And this is the simple php code of the registration:
<?php
require "init.php";
$username = $_POST["username"];
$password = $_POST["password"];
$number = $_POST["number"];
$mpt = "1";
$sql_query = "insert into Users values( '$mpt' , '$number' , '$username' , '$password' , '$number', '$mpt' , '$mpt' , '$mpt' , '$mpt' , '$mpt' , '$mpt' , '$mpt' );";
if ( mysqli_query ( $res , $sql_query ) )
{
echo "<h3> Data Insert Success...".$number.$password.$username.$_POST["password"]."<h3>";
}
else
{
echo "Data Insert fail: Error:".mysqli_error($res).$number.$password.$username;
}
?>
Can someone help me????
I actually dont know java i know the basics but i haven't used it in 3 years, so i dont know how you are getting the value from the user from the post method to php. However you can use the url as get method to get input from the user.
"myDomain/register.php?username=abc&password=qwqw1w1"
and then get it as a get funtion in php. Or you can first take the user input in a variable and then send them to php using POST method, that should work
$username = $_GET["username"];
$password = $_GET["password"];
$number = $_GET["number"];
I have a simple android app that needs to send a message to my PHP server, which will return some data back. I am able to get the data returned from the server, but I can't send any. It's probably something stupid, but I can't figure it out. Note that the url here isn't the real url.
public void addUser(User user, String password) throws Exception {
URL url = new URL("https://someuser.c9users.io/service.php");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
// set Timeout and method
conn.setRequestMethod("POST");
conn.setReadTimeout(7000);
conn.setConnectTimeout(7000);
conn.setRequestProperty("op", "adduser");
conn.setDoOutput(true);
conn.setRequestProperty("username",user.getUserName());
conn.setRequestProperty("email",user.getEmail());
conn.setRequestProperty("password", password);
if(user.getBirthDate() != null)
conn.setRequestProperty("birthdate", user.getBirthDate().toString());
if(user.getProfImage() != null)
conn.setRequestProperty("profile_image", "some path to img");
//conn.connect(); if I leave the code it does NoFileFoundException. why?
InputStream is = conn.getInputStream();
String result="";
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result += inputLine;
}
}
my php code:
function print_post_get() {
echo "post&get vals: ";
foreach($_POST as $key => $value) {
echo $key.":".$value." \n";
}
foreach($_GET as $key => $value) {
echo $key.":".$value." \n";
}
}
//print all post and get
print_post_get();
//get method form post
if(empty($_POST['op']))
die('no operation?');
switch($_POST['op']) {
case 'adduser':
$retval = adduser();
if($retval) //couldn't add user
echo $retval;
break;
case 'removeuser':
$retval = removeuser();
if($retval)
echo $retval;
break;
case 'getuser':
$retval = getuser();
echo $retval;
break;
default:
echo "unknow op.";
break;
}
I recently had a similar problem. I found setRequestProperty adds to your headers, not the POST body. But the
conn.setDoOutput(true)
allows you to connect to the
outStream = conn.getOutputStream()
Now you can create the POST data with a android.net.Uri.Builder.
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("username",user.getUserName())
.appendQueryParameter("email",user.getEmail());
Write to the stream, the getEncodedQuery()
try (OutputStream outStream = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(outStream, "UTF-8"))) {
String query = builder.build().getEncodedQuery();
writer.write(query);
}
Now you can POST your request with conn.