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

如何使用java和json web服务创建登录,java,php,json,Java,Php,Json,我想创建一个swing应用程序,并使用json引用数据库。我尝试过,但没有成功,我对json还不熟悉。我想使用webservice访问数据库。 下面是我的代码 Login.java String username=jTextField1.getText(); String password=jPasswordField1.getText(); JSONObject obj = new JSONObject(); obj.put("username", username); o

我想创建一个swing应用程序,并使用json引用数据库。我尝试过,但没有成功,我对json还不熟悉。我想使用webservice访问数据库。 下面是我的代码

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 这是我的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);
}

什么是错误,伙计?它不返回任何正确或错误。我认为错误在于php代码。您是否注意到您没有从php页面返回任何内容以在Java端读取?请检查您的PHP代码,因为这与Java端无关。我建议您从PHP页面获得JSON响应。这里有一个解决方案:我返回true或false布尔表达式。这还不够吗?@user2508416看起来你对web开发一无所知。web响应不能是简单的布尔、int或您的类型。也许你想改用Web服务。