使用HttpURLConnection从Android发送HTTP POST

时间:2014-04-09 20:25:54

标签: android mysql database http-post httpurlconnection

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

编辑:这太简单了......请阅读以下代码段中的注释:

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,也会将值写入数据库。我完全糊涂了......

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

我同意Salivan。在不检查响应代码的情况下,在将POST发送到服务器之前,将重置tcp连接。但没人讨论这个问题。有什么理由吗?

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