【发布时间】:2015-11-25 15:12:55
【问题描述】:
我正在使用 HttpURLConnection 从 mysql 数据库表中检索图像的路径。但我只需要给定用户名的路径,所以我使用 POST 将用户名拖到服务器。
public class ImageDownload {
public String sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
StringBuilder sb = new StringBuilder();
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String response;
while ((response = br.readLine()) != null){
sb.append(response);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}}
在我的 doInBackground 中,我设置了要传递的用户名并调用 ImageDownload 类
ImageDownload rh = new ImageDownload();
@Override
protected String doInBackground(String... strings) {
UserLocalStore userLocalStore = new UserLocalStore(GridViewActivity.this);
String username = userLocalStore.getLoggedInUser().username;
HashMap<String,String> data = new HashMap<>();
data.put(KEY_USERNAME, username);
String result = rh.sendPostRequest(GET_IMAGE_URL,data);
return result;
}
而服务器上的php是
<?php
require_once('dbConnect.php');
$username = $_POST["username"];
$sql = "select image from photos WHERE username =?";
$res = mysqli_prepare($con,$sql);
mysqli_stmt_bind_param($res, "s", $username);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,array('url'=>$row['image']));
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
?>
我有一个问题。
返回 sb.toString()
ImageDownload 类为空!我检查了服务器,似乎 $_POST 有问题,因为它显然是空的。事实上,如果我删除条件“WHERE 用户名 =?”在服务器 php 文件上,我成功地从数据库表中检索了整个路径列表。但这不是我需要的。 $_POST 变量有什么问题,为什么不能正确上传? 非常感谢
【问题讨论】:
-
$_POST 可能没有问题。要么您没有在 android 中正确发布帖子,要么服务器上的某些东西将提交重定向到其他地方并丢失了用户名键:值。开始调试:
var_dump($_POST, $_SERVER['request_method']),看看什么到达,以及它是如何到达的。 -
也许是 $_POST['KEY_USERNAME'] ?
-
感谢您的提示。好吧,我实际上调试并使用了 var_dump 似乎 $username 设置正确!!! “giacomo”是我得到的,是正确的用户名。那么为什么不工作呢?
标签: php android mysql post httpurlconnection