我试图了解如何通过 Android 应用程序链接到 PHP/MySQL,以便从已在数据库上的用户获取登录信息。
我发现一种方法是访问 PHP 页面,从应用程序发送输入的数据并将其发布到 PHP 的参数上,PHP 本身应该查找用户引用,并在用户存在或存在时返回不是。
但是,我寻找如何做到这一点的每个地方都太复杂或没有很好解释。 所以我正在寻找一种方法来做到这一点,如果你知道一些教程或注释良好的代码,你可以提供给我学习,这对我来说非常有用。或者你们中的任何人可以教我如何做或从哪里开始学习,那就太好了。
提前非常感谢您。
最佳答案
对于这种交互,我使用以下代码:
public static String httpPost(String address, List<NameValuePair> parameters) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(address);
InputStream inputStream = null;
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
try {
httpPost.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
reader = new BufferedReader((new InputStreamReader(inputStream)));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
}catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (reader != null)
reader.close();
if (inputStream != null)
inputStream.close();
}catch (Exception e) {
e.printStackTrace();
}
}
return sb.toString();
}
您必须向此函数传递一个 String
(PHP 脚本的 URL),以及包含要传递给脚本的数据的 NameValuePair
列表,然后它从服务器返回答案。
如果你想用它来登录,你可以使用类似的东西:
public boolean login(String username, String passwd) {
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("username", username);
parameters.add(new BasicNameValuePair("password", passwd);
String result = httpPost("http://test.com/login.php", parameters);
return result.equals("ok");
}
关于java - Android链接PHP到MySQL以登录应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19960620/