Stan Kurilin
Stan Kurilin

Reputation: 15792

several requests from one HttpURLConnection

How can I do several request in one HttpURLConnection with Java?

 URL url = new URL("http://my.com");
 HttpURLConnection connection = (HttpURLConnection)url.openConnection();
 HttpURLConnection.setFollowRedirects( true );
 connection.setDoOutput( true );
 connection.setRequestMethod("GET"); 

 PrintStream ps = new PrintStream( connection.getOutputStream() );
 ps.print(params);
 ps.close();
 connection.connect();
 //TODO: do next request with other url, but in same connection

Thanks.

Upvotes: 16

Views: 13049

Answers (2)

StaxMan
StaxMan

Reputation: 116610

Beyond the correct answer, maybe what you actually want is reuse of the underlying TCP connection, aka "persistent connections", which are indeed supported by JDK's HttpURLConnection. So you don't need to use other http libs for that reason; although there are other legitimate reason, possibly performance (but not necessarily, depends on use case, library).

Upvotes: 3

Carl Smotricz
Carl Smotricz

Reputation: 67800

From the Javadoc:

Each HttpURLConnection instance is used to make a single request.

The object apparently isn't meant to be re-used.

Aside from a little memory thrashing and inefficiency, there's no big problem with opening one HttpURLConnection for every request you want to make. If you want efficient network IO on a larger scale, though, you're better off using a specialized library like Apache HttpClient.

Upvotes: 18

Related Questions