0

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

Giacomo C
  • 1
  • 3
  • there's probably nothing wrong with $_POST. either you're not doing the post correctly in android, or something on the server is redirecting the submission elsewhere and losing the username key:value. start debugging: `var_dump($_POST, $_SERVER['request_method'])`, see what arrived, and how it arrived. – Marc B Nov 25 '15 at 15:17
  • Perhaps $_POST['KEY_USERNAME'] ? – Svetoslav Nov 25 '15 at 15:23
  • thanks for the tips guys. Well I actually debugged and using the var_dump it seems that $username is correctly set!!! "giacomo" is what i get back and is the correct username. So why is not working ? – Giacomo C Nov 25 '15 at 15:38

1 Answers1

0

According to this answer, you need to set these properties to your POST request in order to make it work:

conn.setRequestProperty( "Content-type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "Accept", "*/*" );
Community
  • 1
  • 1
Phate01
  • 2,499
  • 2
  • 30
  • 55