从 HttpURLConnection post 接收数据

Receive data back from HttpURLConnection post

我目前正在 post 使用此功能将数据发送到 php 页面:

private void postData(HashMap<String, String> postDataParams, String urlString)
{
    //I'm using HTTP currently but we should use HTTPS but we need an SSL certificate

    URL url;
    String response = "";
    try {
        url = new URL(urlString);

        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(getPostData(postDataParams));
        writer.close();
        os.close();
        int responseCode=conn.getResponseCode();

        if (responseCode == HttpURLConnection.HTTP_OK) {
            String line;
            BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((line=br.readLine()) != null) {
                response+=line;
            }
        }
        else {
            response="";
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    Log.i(null, response);

}

private String getPostData(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();
}

我想接收 php 页面在 post 完成后发回的数据。我该怎么做?我会回应 php 页面上的内容并阅读吗?如果是这样,我可以在此函数的哪个位置读取响应?

谢谢

此代码中的可变响应 returns 无论您在 php 中回显什么,如 Clairvoyant 所述。