【问题标题】:Receive data back from HttpURLConnection post从 HttpURLConnection 帖子接收数据
【发布时间】:2015-06-08 09:58:35
【问题描述】:

我目前正在使用此函数将数据发布到 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 页面上回显某些内容并阅读它吗?如果是这样,我可以在该函数的哪个位置读取响应?

谢谢

【问题讨论】:

  • 您已经从 post 获得响应,只需从 postData() 返回该响应变量即可。
  • 啊,是的,我没有意识到,抱歉这么愚蠢的问题
  • 太棒了!!!很好。

标签: php android post httpurlconnection


【解决方案1】:

此代码中的变量 response 返回您在 php 中回显的任何内容,如 Clairvoyant 所述。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    相关资源
    最近更新 更多