I want to create a swing application and refer to the database using json.I tried but it did not work and i'm new to json.I want to access the database using webservice. Below my code.
Login.java
String username=jTextField1.getText();
String password=jPasswordField1.getText();
JSONObject obj = new JSONObject();
obj.put("username", username);
obj.put("password", password);
try {
HttpClient httpclient= new DefaultHttpClient();
HttpResponse response;
HttpPost httppost= new HttpPost("http://localhost/kolitha/json_test/index.php");
StringEntity se=new StringEntity ("myjson: "+obj.toString());
httppost.setEntity(se);
System.out.print(se);
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
response=httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println("result is "+responseBody);
}
catch (Exception e) {
e.printStackTrace();
System.out.print("Cannot establish connection!");
}
index.php here is my php file and i want to get the json object and parse username and password to query and send the response java application.
<?php
$json = file_get_contents('php://input',0,null,null);
$json_output = json_decode($json);
$username;
$password;
foreach($json_output -> details as $detail)
{
$username = $detail -> username;
$password = $detail -> password;
}
$login_result = false;
$connect = mysql_connect('localhost', 'root', '');
IF(!$connect)
{
die('Failed Connecting to Database: '.mysql_error());
}
$d = mysql_select_db("kolitha_json_test");
if (!$d)
{
echo "db not selected";
}
$sql = "SELECT * FROM login WHERE username='$username' AND password='$password' ";
$result = mysql_query($sql) or die (mysql_error());
if (!$result){
$login_result = false;
return $login_result;
die("Could not run the Query ".mysql_error());
} else {
$login_result = true;
return $login_result;
}
?>