簡體   English   中英

如何使用Java和JSON Web服務創建登錄名

[英]how to create a login with java and json web service

我想創建一個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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM