[英]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.