简体   繁体   English

JAVA:从 HTTPS URL 获取响应代码的最快和最好的方法是什么?

[英]JAVA: What's the fastest and best way to get a response code from HTTPS URL?

    private int getResponse(String url) throws Exception {

    try {
       URL check = new URL(url);
       HttpsURLConnection connection = (HttpsURLConnection)check.openConnection();
       connection.setRequestMethod("GET");
       connection.setConnectTimeout(5000);
       connection.connect();

       return(connection.getResponseCode());

    } catch (java.net.SocketTimeoutException e) {
           return getResponse(url);
    }

}

Is there a faster way to get the response code from a URL than HttpsURLConnection?有没有比 HttpsURLConnection 更快的从 URL 获取响应代码的方法?

I tried HeadMethod from the HTTP Client Commons but that's not that much faster.我尝试了 HTTP Client Commons 中的 HeadMethod,但这并没有那么快。

Thanks in advance提前致谢

I strongly suspect that differences will be absolutely minimal, when compared to normal internet delays and the network stack that Java itself is using (provided by the underlying OS).我强烈怀疑,与正常的互联网延迟和 Java 本身使用的网络堆栈(由底层操作系统提供)相比,差异绝对是最小的。

While making 1 request will incur in roughly the same overhead regardless of library (as long as it is not completely broken; both Apache Commons and JDK are ok), if you are going to make multiple requests, there are several things that will dramatically improve performance:虽然无论库如何,发出 1 个请求都会产生大致相同的开销(只要它没有完全损坏;Apache Commons 和 JDK 都可以),如果你要发出多个请求,有几件事会显着改善表现:

  • If you need to complete several requests as soon as possible, and do not need each one to complete before you can start others, then go parallel.如果您需要尽快完成多个请求,并且不需要每个请求都完成后才能启动其他请求,那么请并行执行。 A useful pointer may be https://github.com/AsyncHttpClient/async-http-client (part of Project Grizzly; uses NIO for non-blocking, highly scalable communication)一个有用的指针可能是https://github.com/AsyncHttpClient/async-http-client(Project Grizzly 的一部分;使用 NIO 进行非阻塞、高度可扩展的通信)
  • If you will perform additional requests from the same site, then you will see a dramatic performance improvement (> 2x) if you use the keep-alive header and reuse the same connection for several requests.如果您将执行来自同一站点的其他请求,那么如果您使用 keep-alive 标头并对多个请求重用相同的连接,您将看到显着的性能改进(> 2 倍)。 This is due to the high setup costs of HTTPS connections.这是因为 HTTPS 连接的设置成本很高。 More information at HTTP vs HTTPS performance (and a nice diagram here ).有关HTTP 与 HTTPS 性能的更多信息(以及此处的精美图表)。 First-time HTTPS requests need 2 round-trips to negotiate encryption before any data is exchanged;在交换任何数据之前,首次 HTTPS 请求需要 2 次往返来协商加密; further requests can avoid the handshake.进一步的请求可以避免握手。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM