如何使用java和jsonweb服务创建登录


how to create a login with java and json web service

我想创建一个swing应用程序,并使用json引用数据库。我试过了,但没有成功,我是json的新手。我想使用Web服务访问数据库。在我的代码下面。

登录.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这是我的php文件,我想获得json对象并解析用户名和密码,以查询和发送响应java应用程序。

<?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;
    }
     ?>

尝试添加

request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));

并检查响应是否有实体

 HttpResponse response = client.execute(request);
 HttpEntity entity = response.getEntity();
 if (entity != null) {
   InputStream instream = entity.getContent();
   String responseBody = RestClient.convertStreamToString(instream);
    System.out.println("result is "+responseBody);
}