Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 542
Stan Kurilin Avatar asked Mar 16 '10 19:03

Stan Kurilin


2 Answers

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.

like image 62
Carl Smotricz Avatar answered Sep 21 '22 13:09

Carl Smotricz


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).

like image 31
StaxMan Avatar answered Sep 23 '22 13:09

StaxMan