简体   繁体   中英

Android HttpURLConnection POST not working.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM