java - 处理服务器响应时减少执行时间?
问题描述
我有一台服务器,我需要从中获取一些数据。一开始,我使用curl
来获得原始JSON
响应,它很快但对我来说还不够。我需要将原始格式转换JSON
为某种特殊格式。
因此,我尝试使用java.net.HttpURLConnection
来编写这样的脚本。
这是我的代码片段:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
........
url="xxxx" //It is not the localhost but the server on other region
HttpURLConnection conn = (HttpURLConnection) new URL(url.toString()).openConnection();
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == 200) {
StringBuffer buffer = new StringBuffer();
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
long startTime = System.currentTimeMillis();
//The format of response is JSON
while ((str = bufferedReader.readLine()) != null) {
//read and convert the raw data to some special data struct
//The time overhead of this part is trivial
}
..........
当我尝试获取一些数据(即仅包含几行)时,上面的代码段不会被while(xxxx)
明显卡住。但是,随着我的数据量的增加(超过3000行),太多的次数while ((str = bufferedReader.readLine()) != null)
使得总时间无法接受。
谁能给我一些建议:
- 基于
HttpURLConnection
,如何优化我的代码以减少额外的时间? - 是否存在一些好的 Java 第 3 部分替代方案
HttpURLConnection
并适合我在这种高延迟关键场景下工作? while
是否可以在没有循环的情况下一次获取内容?
附加:
从本地主机:
解决方案
推荐阅读
- java - 没有为类 org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer 找到序列化程序,也没有发现创建 BeanSerializer 的属性
- php - Wordpress在functions.php中获取隐藏输入字段的值
- mysql - 巨大的 INSERT 列表的 ProgressBar - UPDATE 查询
- angular - 如何在材料设计 Angular 6 中设置时间选择器?
- java - Intellij Spring Boot 运行无法自动加载 application.yml
- c# - Identity Server 4 刷新令牌存储
- chef-infra - 一个节点可以是多个厨师环境的一部分吗
- javascript - 如何以 SEP 1 - 15 的格式在 google appscript 中获取当前月份?
- linux - Eth0 用于传入和 eth1 用于传出连接 NGINX 配置?
- node.js - Redis 在 nodejs 中返回 true