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!! :)