有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java我无法在php中解码json对象

这是我的java代码,它发出http请求并将json对象发送到php脚本

登录。爪哇

    String username = jTextField1.getText();
    String password = jPasswordField1.getText();

    JSONObject obj = new JSONObject();

    obj.put("username", username);
    obj.put("password", password);

    //JSONArray list = new JSONArray();
    //list.add(username);
    //list.add(password);


    //obj.put("logindata", list);
    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");
        System.out.println(obj.toString());

        //response = httpclient.execute(httppost);

        HttpGet httpget = new HttpGet("http://localhost/kolitha/json_test/index.php");
        response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        System.out.println(EntityUtils.toString(entity));



    } catch (Exception e) {
        e.printStackTrace();
        System.out.print("Cannot establish connection!");

    }

这是我的索引。php脚本,我无法从json对象提取用户名和密码

索引。php

$obj = json_decode(file_get_contents('php://input'));

$username=$obj->{'username'};
$password=$obj->{'password'};


$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());
$count=mysql_num_rows($result);

 // If result matched $myusername and $mypassword, table row must be 1 row
if($count==1)
{
echo "true";
}
else
 {
echo "false";
}
?>

共 (2) 个答案

  1. # 1 楼答案

    好的,我留下了一条评论,但似乎没有人注意到一条评论。错误在Java代码中

    StringEntity se = new StringEntity("myjson" + obj.toString());
    

    它向名为myjson的json字符串添加前缀

  2. # 2 楼答案

    为什么同时使用HttpPostHttpGet您正在将字符串实体添加到HttpPost请求,而未使用它

    而您使用的是Httpget,其中未设置您的用户名和密码(因此显然没有与Httpget请求相关联的json数据)

    在此进行更改

     response = httpclient.execute(httppost);//don comment this line
    

    如果您使用的是httppost,请在此处添加注释

    //HttpGet httpget = new HttpGet("http://localhost/kolitha/json_test/index.php");
    //response = httpclient.execute(httpget);