Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of HttpURLConnection class's setDoOutput & setDoInput methods

Tags:

java

android

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 );
like image 757
Android Team Avatar asked Apr 10 '15 10:04

Android Team


People also ask

What is httpurlconnection class in Java?

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 setdooutput?

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.

What is the urlconnection class?

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:

How to display source code of a webpage by urlconnecton class?

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.


1 Answers

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.

like image 147
Simas Avatar answered Sep 22 '22 18:09

Simas