来自一个 HttpURLConnection 的多个请求

发布于 2024-08-25 13:19:10 字数 500 浏览 3 评论 0原文

如何使用 Java 在一个 HttpURLConnection 中执行多个请求?

 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

谢谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一人独醉 2024-09-01 13:19:10

来自 Javadoc:

每个 HttpURLConnection 实例都用于发出单个请求。

该物体显然不适合重复使用。

除了一点点内存消耗和效率低下之外,为您想要发出的每个请求打开一个 HttpURLConnection 并没有什么大问题。不过,如果您想要更大规模的高效网络 IO,那么最好使用专门的库,例如 Apache HttpClient

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.

我早已燃尽 2024-09-01 13:19:10

除了正确答案之外,也许您真正想要的是重用底层 TCP 连接,即“持久连接”,JDK 的 HttpURLConnection 确实支持这种连接。因此,您不需要因此而使用其他 http 库;尽管还有其他合理的原因,可能是性能(但不一定,取决于用例、库)。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文