开发者

several requests from one HttpURLConnection

开发者 https://www.devze.com 2022-12-22 22:53 出处:网络
开发者_如何学JAVAHow can I do several request in one HttpURLConnection with Java? URL url = new URL(\"http://my.com\");

开发者_如何学JAVAHow 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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号