Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't switch HttpURLConnection method to POST

Tags:

java

android

I am trying to send an HTTP POST request to a URL, using HttpsUrlConnection. here is what i am trying to do:

URL requestedUrl = null;
HttpURLConnection urlConnection = null; 
try {
            requestedUrl = new URL("https://www.test.local/login/");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            urlConnection = (HttpsURLConnection) requestedUrl.openConnection();

            try {
                urlConnection.setRequestMethod("POST");
            } catch (ProtocolException e1) {
                e1.printStackTrace();
            }
            urlConnection.setRequestProperty("Content-Type","application/json");
            urlConnection.setRequestProperty("Accept", "application/json");
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            urlConnection.setUseCaches(false);
            urlConnection.setConnectTimeout(1500);

        try {
                urlConnection.connect();
            } catch (IOException e) {
                e.printStackTrace();
            }

When debugging i see that the RequestMethod remains GET, any idea why?

Thanks in advance.

like image 534
user3104682 Avatar asked Nov 29 '25 11:11

user3104682


1 Answers

With the given code you should not be able to see a request at all in your network trace.

In the given snippet you only open a connection via urlConnection.connect(), but you do not perform an actual request like with urlConnection.getContent(). The connect() method alone does not perform the request.

Replacing your last try-catch block with the following should send a POST request:

try {
    urlConnection.connect(); // open the connection
    urlConnection.getContent(); // send prepared request
} catch (IOException e) {
    e.printStackTrace();
}
like image 147
fishi0x01 Avatar answered Dec 01 '25 01:12

fishi0x01



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!