Home > Net >  How to properly post url in android with java using HttpURLConnection
How to properly post url in android with java using HttpURLConnection

Time:02-10

I try to use HttpURLConnection to send a post request to my local (xampp) server with an url like this http://xxx.xxx.0.3/Company/index.php/booking/c200/p-205/2025-02-09 8:2 , the server php file take param in url and send data to mysql database .

The url works fine on postman agent , and even another get method request works smooth in the android application .

Yet when i try the post method with following code :

public void postOrder() {
        TextView tv = findViewById(R.id.tv1);
        Thread t = new Thread( new Runnable() {
            @Override
            public void run() {
                HttpURLConnection conn = null;
                try {
                    String link = "http://xxx.xxx.0.3/Company/index.php/booking/c200/p-205/2025-02-09 8:2";
                    URL url = new URL(link);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setReadTimeout(10000 /*ms*/);
                    conn.setConnectTimeout(15000 /*ms*/);
                    conn.connect();
                }
                catch (IOException e) {
                    Log.d("HTTP error: ", e.toString());
                }
                finally {
                    conn.disconnect();
                }
            }
        } );
        t.start();
}

It never sent the url and thus no data is stored to database .

And with 6 hours of trial and error , google and searching , i added this line of code :

InputStream is = conn.getInputStream();

And it finally works . Please answer me why it only works after adding this line of code , what does it do ? I thought the url is triggered right after conn.connect();

CodePudding user response:

Calling connect() only connects, but it doesn't send anything yet. Call getResponseCode() to force the request to be sent. That method is safer than getInputStream() which will throw an exception if the response is not a 2xx (in which case you'd need getErrorStream()).

  •  Tags:  
  • Related