使用HttpURLConnection时,$ _POST在mysql上为空

时间:2015-11-25 15:12:55

标签: php android mysql post httpurlconnection

我正在使用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 username =?”在服务器上的php文件我成功从数据库表中检索了整个路径列表。但这不是我需要的。 $ _POST变量有什么问题,为什么没有正确上传? 非常感谢

1 个答案:

答案 0 :(得分:0)

根据此answer,您需要将这些属性设置为POST请求才能使其正常工作:

conn.setRequestProperty( "Content-type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "Accept", "*/*" );