我使用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();
}}这里是我设置要传递和调用ImageDownload类的用户名的doInBackground
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()
from ImageDownload类为空!我检查了服务器,$_POST似乎有问题,因为它显然是空的。事实上,如果我删除条件"WHERE username =?“在服务器php文件上,我成功地从数据库表中检索了整个路径列表。但这不是我想要的。$_POST变量有什么问题?为什么上传不正确?非常感谢
发布于 2015-11-25 23:35:36
根据此answer,您需要将这些属性设置为POST请求才能使其工作:
conn.setRequestProperty( "Content-type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "Accept", "*/*" );https://stackoverflow.com/questions/33920024
复制相似问题