我正在尝试使用where条件从MySQL数据库获取数据到我的安卓应用程序。我已经创建了一个获取数据的方法。此方法将所有数据作为单个列中的字符串数组提供。看看下面的方法:
String adress = "http://myserver_link/get_data.php";
InputStream inputStream = null;
String line = null, result = null, data[];
private void get_data(){
try {
URL url = new URL(adress);
HttpURLConnection httpsURLConnection = (HttpURLConnection) url.openConnection();
httpsURLConnection.setRequestMethod("GET");
inputStream = new BufferedInputStream(httpsURLConnection.getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// read input stream into a string
try{
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null){
stringBuilder.append(line + "\n");
}
inputStream.close();
result = stringBuilder.toString();
}
catch (Exception e) {
e.printStackTrace();
}
// Parse json data
try{
JSONArray jsonArray = new JSONArray(result);
JSONObject jsonObject = null;
data = new String[jsonArray.length()];
for (int i=0; i<jsonArray.length(); i++){
jsonObject = jsonArray.getJSONObject(i);
data[i] = jsonObject.getString("user_adress"); // column name
}
}
catch (Exception e){
e.printStackTrace();
}
}
这是我的get data java方法。我的get_data.php代码是:
<?php
require "conn.php";
$query = mysqli_query($conn, "select * from android_data");
if ($query) {
while ($row = mysqli_fetch_array($query)) {
$flag[] = $row;
}
print(json_encode($flag));
}
$conn->close();
?>
现在,我想像下面这样编写我的get_data.php文件:
<?php
require "conn.php";
$user_name = $_POST["username"];
$query = mysqli_query($conn, "select * from android_data where username='$user_name'");
if ($query) {
while ($row = mysqli_fetch_array($query)) {
$flag[] = $row;
}
print(json_encode($flag));
}
$conn->close();
?>
但是如何在我的应用程序中使用get_data() java方法发送用户名呢?
发布于 2018-03-09 16:08:18
您可能应该将其作为URL上的参数发送...
String adress = "http://myserver_link/get_data.php?username=xxxxx";
Java暂时还没有完成,但是您可以使用适当的xxxxx值创建此字符串。
然后,它将作为$_GET["username"]
而不是$_POST["username"]
传入。所以只需替换这一行
$user_name = $_POST["username"];
使用
$user_name = $_GET["username"];
发布于 2018-06-04 04:17:57
或者,您可以在Java代码中将请求方法更改为POST。
https://stackoverflow.com/questions/49189141
复制相似问题