8

I am calling POST webservice with below line of code.

I am not clear with connection.setDoOutput( true ); and connection.setDoInput( true );

Can you please elaborate me purpose of this code ?

Can I use same code with GET or not ?

URL url = new URL( "http://xxxxxx.com" );
HttpURLConnection connection = ( HttpURLConnection ) url.openConnection();
connection.setRequestMethod( "POST" );
connection.setDoOutput( true );
connection.setDoInput( true );
connection.setUseCaches( false );

1 Answer 1

15

setDoOutput(true) is used with POST to allow sending a body via the connection:

OutputStream os = connection.getOutputStream();
os.write(body);
os.flush();
os.close();

setDoInput(true) is used to fetch the response and is true by default.

When using a different method e.g. GET, you have nothing to pass to the connection, so an OutputStream is not necessary.

Sign up to request clarification or add additional context in comments.

Comments