从HttpURLConnection帖子

时间:2015-06-08 09:58:36

标签: php android post httpurlconnection

我目前正在使用此功能将数据发布到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页面发回的数据。我该怎么做?我会在php页面上回应一些内容并阅读它吗?如果是这样,我可以在这个函数中读到响应吗?

由于

1 个答案:

答案 0 :(得分:0)

此代码中的变量响应将返回您在PHP中回显的所有内容,如Clairvoyant所述。