我正在 android 中构建这个演示项目以供临时使用。我需要在服务器数据库上运行查询并从中返回结果。我陷入了从服务器部分检索数据的困境。这是我的文件。
主要 Activity :
public void callit(View view) {
final String url = "http://xyz.000webhostapp.com/login.php?mail=abcxyz@gmail.com";
new Thread() {
@Override
public void run() {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
JSONTokener tokener = new JSONTokener(json);
JSONArray finalResult = new JSONArray(tokener);
Toast.makeText(MainActivity.this, "This is my Toast message!",
Toast.LENGTH_LONG).show();
} catch (IOException e) {
} catch (JSONException e) {
e.printStackTrace();
}
} else {
//Closes the connection.
try {
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
} catch (IOException e) {
}
}
}
catch (ClientProtocolException e)
{
}
catch (IOException e)
e.printStackTrace();
{
}
}
}.start();
}
这是我的 php 脚本文件:
<?php
define('HOST_NAME','localhost');
define('USER_NAME','abc');
define('PASSWORD','xyz');
define('DATABASE','pqr');
$con = mysqli_connect(HOST_NAME,USER_NAME,PASSWORD,DATABASE);
if(!$con)
{
die('Could not connect: ' . mysqli_erro());
}
else
{
$email = $_GET["mail"];
$sql="SELECT * FROM user WHERE email='$email' ";
$result=mysqli_query($con, $sql);
if(!empty($result))
{
while ($row = mysqli_fetch_array($result))
{
$response["mb"]=$row["mobile"];
}
echo(json_encode($response));
}
mysqli_close($con);
}
?>
但我不知道这些数据到底如何存储在 json 文件中?正如您从 php 文件中看到的,我只需要从数据库返回给定电子邮件 ID 的手机号码。 php 脚本工作正常,我在浏览器中测试了它。
我只需要找到一种方法将该值发送到我的 Android 应用程序并烘烤该手机号码。
询问我的问题是否有任何部分不明确。抱歉英语不好。
最佳答案
如果你用 php 开发一个 Rest api,那就太好了,here是一个附加的在线教程示例,用于休息,或者如果安全性(或正确执行操作)不是很重要,如果它是一个学校项目,那么您只需将其转换为 json ,只需在您的 php 文件中创建一个简单的 php 页面,您可以在其中获取电话号码作为查询参数 $email = $_GET["mail"];就像你已经得到的那样,只需从 android 简单地获取页面,你不需要将其转换为 json 这是回显电话号码的简单 PHP 程序和获取该电话号码的 java 代码
<?php
echo "00923244549369"
?>
在您的代码中,您将在末尾回显电话号码,就像它一样
public static void main(String args[]) {
URL url;
InputStream is = null;
BufferedReader br;
String line;
try {
url = new URL("http://localhost/writers/");
is = url.openStream(); // throws an IOException
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (Exception mue) {
mue.printStackTrace();
} finally {
try {
if (is != null)
is.close();
} catch (IOException ioe) {
// nothing to see here
}
}
}
输出:00923244549369
关于java - 如何从 php 向 java/android 发送和检索数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44470964/