我有一个 android 应用程序,它将 JSON 信息发送到 web 服务以验证信息。我使用 Kate 作为网络服务的编辑器。JSON 和 php webservices 的概念对我来说是新的。我通常用java编写代码。
JSONObject jsonObject = new JSONObject();
String userID = "";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(loginURI);
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams,10000);
try {
jsonObject.put("username", username);
Log.i("username", jsonObject.toString());
jsonObject.put("password", password);
Log.i("password", jsonObject.toString());
StringEntity stringEntity = new StringEntity(jsonObject.toString());
stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(stringEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
userID = EntityUtils.toString(httpResponse.getEntity());
Log.i("Read from server", userID);
}
}catch (IOException e){
Log.e("Login_Issue", e.toString());
}catch (JSONException e) {
e.printStackTrace();
}
return userID;
}
我在网上找到了 StringEntity 代码,并认为它会起作用。我不明白 HttpPost 的 StringEntity 的用途。
这是我用 php 编写的 web 服务。
include('dbconnect.php');
$tablename = 'users';
//username and password sent from android
$username=$_POST['myusername'];
$password=$_POST['mypassword'];
//protecting mysql injection
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
#$array = array($username,$password);
$sql = "SELECT first_name FROM $tablename WHERE u_username='$username' AND u_password=MD5('$password')";
//Querying the database
$result=mysql_query($sql);
if(!$result){
die(mysql_error();
}
//If found, number of rows must be 1
if((mysql_num_rows($result))==1){
//creating session
session_register("$username");
session_register("$password");
print true;
}else{
print false;
}
mysql_close();
我不太确定“用户名”和“密码”是否从 android 应用程序正确发送到 web 服务。我怎样才能验证这一点?Web 服务和 Java 代码是否编写得很好,可以以 JSON 格式发送信息?
当我在浏览器上访问网络服务时,出现以下错误: Parse error: parse error in E:\wamp\www\mobile.dcl.mu\webserver\login.php on line 24
先感谢您。