java 来自一个 HttpURLConnection 的多个请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2457538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
several requests from one HttpURLConnection
提问by Stan Kurilin
How can I do several request in one HttpURLConnection with Java?
如何使用 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
Thanks.
谢谢。
回答by Carl Smotricz
From the Javadoc:
来自 Javadoc:
Each HttpURLConnection instance is used to make a single request.
每个 HttpURLConnection 实例用于发出单个请求。
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.
除了一点内存颠簸和低效之外,为您想要发出的每个请求打开一个 HttpURLConnection 没有什么大问题。但是,如果您想要更大规模的高效网络 IO,最好使用像Apache HttpClient这样的专用库。
回答by StaxMan
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).
除了正确答案之外,也许您真正想要的是重用底层 TCP 连接,也就是“持久连接”,JDK 的 HttpURLConnection 确实支持这种连接。因此,您不需要为此使用其他 http 库;尽管还有其他合理的原因,可能是性能(但不一定,取决于用例、库)。

