I am using an HttpURLConnection to retrieve images' path from mysql database table. But I need the path only for a given username so I am using POST to drag the username to the server.
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();
}}
Here my doInBackground where i set the username to pass and call the ImageDownload class
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;
}
And the php on the server is
<?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);
?>
I have got an issue. The
return sb.toString()
from ImageDownload class is empty! I checked on the server and it seems there is something wrong with the $_POST cause it is apparently empty. In fact if I remove the condition "WHERE username =?" on the server php file i successfully retrieve the whole list of path from the database table. But is not what i need. What's wrong with the $_POST variable and why is not uploading correctly? Thanks a lot