2

我想创建一个 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;
    }

     ?>
4

1 回答 1

1

尝试添加

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);
}
于 2013-07-16T05:21:58.700 回答