【问题标题】:Sending HTTP POST from Android with HttpURLConnection使用 HttpURLConnection 从 Android 发送 HTTP POST
【发布时间】:2014-04-09 20:25:53
【问题描述】:

我正在尝试从 Android 应用程序向我的 PHP 编码服务器发送 HTTP POST 请求,该服务器将从请求中接收到的数据放入 MySQL 数据库。如果我使用HttpClientHttpPost 方法,一切正常,但我决定尝试HttpURLConnection 类,因为据说它比旧的HttpClientHttpPost 类更加优化和更新,而且,不幸的是,我无法让它以这种方式工作。我没有收到任何错误或异常,并且设备正在连接到网络,但没有任何反应,给定的值不会写入数据库。请告诉我我做错了什么并给我建议。也许使用HttpClient/HttpPost 方法更好?

这是我的代码:

private void writeToDatabase(URL url, String number, String comment) throws IOException  {
        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.setConnectTimeout(15 * 1000);
        httpConnection.setReadTimeout(10 * 1000);
        httpConnection.setRequestMethod("POST");
        httpConnection.setDoInput(true);
        httpConnection.setDoOutput(true);

        List<NameValuePair> params = new ArrayList<NameValuePair>(3);
        params.add(new BasicNameValuePair("code", "****"));
        params.add(new BasicNameValuePair("number", number));
        params.add(new BasicNameValuePair("comment", comment));

        OutputStream os = httpConnection.getOutputStream();
        BufferedWriter br = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        br.write(getQuery(params));
        br.flush();
        br.close();
        os.close();

        httpConnection.connect();
}

getQuery()函数:

private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;

        for (NameValuePair pair : params) {
            if (first) {
                first = false;
            } else result.append("&");

            result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
        }

        return result.toString();
}

这就是我调用writeToDatabase() 函数的方式和位置:

Thread thread = new Thread() {

    @Override
    public void run () {
        try {
            URL url = new URL("http://www.***.com");
            writeToDatabase(url, "****", "as pats");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
};
thread.start();

编辑:这太奇怪了...阅读以下代码 sn-p 中的 cmets:

private void writeToDatabase(URL url, String number, String comment) throws IOException  {
        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.setConnectTimeout(15 * 1000);
        httpConnection.setReadTimeout(10 * 1000);
        httpConnection.setRequestMethod("POST");
        httpConnection.setDoInput(true);
        httpConnection.setDoOutput(true);

        httpConnection.connect();

        List<NameValuePair> params = new ArrayList<NameValuePair>(3);
        params.add(new BasicNameValuePair("code", "****"));
        params.add(new BasicNameValuePair("number", number));
        params.add(new BasicNameValuePair("comment", comment));

        OutputStream os = httpConnection.getOutputStream();
        BufferedWriter br = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        br.write(getQuery(params));
        br.flush();
        br.close();
        os.close();
        //Everything works just fine with these lines below, but without them, it doesn't work... Why is that?
        BufferedReader in = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            Log.i("ilog", inputLine);
        }

        httpConnection.disconnect();
}

看起来这段代码不起作用的问题是我没有阅读响应。如果我读到这样的回复:

BufferedReader in = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            Log.i("ilog", inputLine);
        }

然后一切都完美无缺。但这是为什么呢?有人可以向我解释一下吗?我非常非常感兴趣!

编辑 2:即使我设置了 httpConnection.setDoOutput(false);,只要我阅读响应,它仍然可以正常工作。即使setDoOutput() 设置为false,值也会写入数据库。我完全糊涂了……

【问题讨论】:

  • 你看过connection.getResponseCode()吗?
  • 没有,但是我检查了html日志,没有遇到任何请求...

标签: android mysql database http-post httpurlconnection


【解决方案1】:

本例先展示connect(),将POST数据写入输出流,检查响应码,关闭输出流。

http://soda815.blogspot.com/2013/09/android-how-to-use-httpurlconnection-to.html

【讨论】:

  • 我的代码只有在我检查响应代码时才有效。但这是为什么呢?请看我编辑的帖子。
【解决方案2】:

我同意萨利文的观点。在不检查响应代码的情况下,tcp 连接将在 POST 发送到服务器之前被重置。但是没有人讨论这个。有什么原因吗?

if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                inputStream = conn.getInputStream();
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    • 2012-12-04
    • 2013-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多