views:

114

answers:

2

Hi! 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.

+3  A: 

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.

Carl Smotricz
I was about to say the same thing, about it not being meant to be reused
Jessica
Have a +1, then! Usually I agonize so long over my answers that everybody beats me to it. :)
Carl Smotricz
+1  A: 

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

StaxMan
@StaxMan : Thanks, but I've already done it with some third part library.
Stas