首页 > 解决方案 > 处理服务器响应时减少执行时间?

问题描述

我有一台服务器,我需要从中获取一些数据。一开始,我使用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) 使得总时间无法接受。

谁能给我一些建议:

附加

从本地主机:

在此处输入图像描述

从远程服务器: 在此处输入图像描述

标签: javahttphttpurlconnection

解决方案


推荐阅读