kotlin HttpURLConnection的getInputStream太慢

wa7juj8i  于 2023-06-24  发布在  Kotlin
关注(0)|答案(1)|浏览(191)

我正在尝试使用HttpURLConnection来获取带有URL的JSON响应。但是,getInputStream()需要太多时间(一小段json文本需要大约500 ms!)导致低效率。下面是我的代码:

val urlStr= "https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1"
    urlCon = URL(urlStr).openConnection() as HttpURLConnection
    val conInputStream = urlCon.inputStream     //主要占时  //takes too much time
    val input = InputStreamReader(conInputStream, "UTF-8")
    reader = BufferedReader(input)
        reader.use {
        reader.forEachLine { sb.append(it) }
    }

有什么方法可以提高回复速度吗?

2vuwiymt

2vuwiymt1#

你确定这和Java/Kotlin有什么关系,除了你和服务器之间的延迟和/或它的响应时间?
我使用Apache Bench工具“ab”,每次命中1次,平均整个事件的响应时间低于100 ms。当然,这并不能证明/反驳Java的getInputStream()很慢--但我建议你在遇到连接缓慢的同一台机器上尝试一些类似的工具。

ab -n 10 "https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1"                                              (project/RP-3589_Health_Data|✚5)
This is ApacheBench, Version 2.3 <$Revision: 1903618 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking cn.bing.com (be patient).....done

Server Software:
Server Hostname:        cn.bing.com
Server Port:            443
SSL/TLS Protocol:       TLSv1.2,ECDHE-RSA-AES256-GCM-SHA384,2048,256
Server Temp Key:        ECDH P-384 384 bits
TLS Server Name:        cn.bing.com

Document Path:          /HPImageArchive.aspx?format=js&idx=0&n=1
Document Length:        905 bytes

Concurrency Level:      1
Time taken for tests:   1.024 seconds
Complete requests:      10
Failed requests:        0
Total transferred:      28180 bytes
HTML transferred:       9050 bytes
Requests per second:    9.76 [#/sec] (mean)
Time per request:       102.411 [ms] (mean)
Time per request:       102.411 [ms] (mean, across all concurrent requests)
Transfer rate:          26.87 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:       46   63  21.6     58     122
Processing:    36   39   2.8     38      44
Waiting:       36   39   2.6     38      44
Total:         83  102  21.4    100     159

Percentage of the requests served within a certain time (ms)
  50%    100
  66%    102
  75%    102
  80%    106
  90%    159
  95%    159
  98%    159
  99%    159
 100%    159 (longest request)

相关问题