简体   繁体   中英

Sending HTTP POST from Android with HttpURLConnection

I am trying to send a HTTP POST request from Android application to my PHP coded server which puts the data received from the request to a MySQL database. If I do it using HttpClient and HttpPost methods, everything works fine, but I decided to try HttpURLConnection class, because it is said to be more optimized and much newer than the old HttpClient and HttpPost classes, and, unfortunately, I can't get it to work this way. I don't receive any errors or exceptions and device is connecting to a network, but nothing happens, the given values are not written to the database. Please tell me what am I doing wrong and advice me. Maybe it is better to use HttpClient/HttpPost method?

This is my code:

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() function:

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

And this is how and where I call the writeToDatabase() function:

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();

EDIT: That's SOO weird... Read the comments in the following code snippet:

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

It looks like the problem why this code didn't work is that I didn't read the response. If I read the response like this:

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

Then everything works just perfectly. But Why is that? Could anybody explain this to me? I'm very very interested!

EDIT 2: Even if I set httpConnection.setDoOutput(false); it still works perfectly as long as I read the response. Values is written to the database even if setDoOutput() is set to false . I'm totally confused...

This example shows connect() first, write the POST data to the output stream, check the response code, close the output stream.

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

I agree with Salivan. Without checking the response code, the tcp connection will be reset before the POST is sent to the server. But no one discusses this. Is there any reason?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM