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 );
Java.net.HttpURLConnection Class in Java Last Updated : 16 Oct, 2019 HttpURLConnection class is an abstract class directly extending from URLConnection class. It includes all the functionality of its parent class with additional HTTP specific features.
What is the function or purpose of HttpURLConnection.setDoInput and HttpURLConnection.setDoOutput? Set the DoInput flag to true if you intend to use the URL connection for input, false if not. The default is true. Set the DoOutput flag to true if you intend to use the URL connection for output, false if not.
The abstract class URLConnectionis the superclass of all classes that represent a communications link between the application and a URL. Instances of this class can be used both to read from and to write to the resource referenced by the URL. In general, creating a connection to a URL is a multistep process:
The openConnection() method of URL class returns the object of URLConnection class. Syntax: Displaying source code of a webpage by URLConnecton class. The URLConnection class provides many methods, we can display all the data of a webpage by using the getInputStream() method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With