【问题标题】:Efficiently making multiple GET requests to the same url in Java在 Java 中有效地向同一个 url 发出多个 GET 请求
【发布时间】:2014-05-10 13:38:23
【问题描述】:

我需要向同一个 URL 发出多个 GET 请求,但查询不同。我将在移动设备 (Android) 上执行此操作,因此我需要尽可能优化。我从观看 Google 的 Android 网络研讨会中了解到,连接到服务器大约需要 200 毫秒,而且进行数据呼叫还涉及各种其他延迟。我只是想知道是否有一种方法可以优化向同一个 URL 发出多个请求的过程以避免其中一些延迟?

到目前为止,我一直在使用以下方法,但我已经调用了 6 次,每个 GET 请求调用一次。

//Make a GET request to url with headers.
//The function returns the contents of the retrieved file

public String getRequest(String url, String query, Map<String, List<String>> headers) throws IOException{
    String getUrl = url + "?" + query;
    BufferedInputStream bis = null;
    try {
        connection = new URL(url + "?" + query).openConnection();
        for(Map.Entry<String, List<String>> h : headers.entrySet()){
            for(String s : h.getValue()){
                connection.addRequestProperty(h.getKey(), s);
            }
        }

        bis = new BufferedInputStream(connection.getInputStream());
        StringBuilder builder = new StringBuilder();
        int byteRead;
        while ((byteRead = bis.read()) != -1)
            builder.append((char) byteRead);

        bis.close();
        return builder.toString();
    } catch (MalformedURLException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    }
}

【问题讨论】:

    标签: java android get request


    【解决方案1】:

    如果对于每个请求,您都期望另一个结果,并且您无法通过在同一请求中添加多个 GET 变量来组合请求,那么您无法避免 6 次调用。

    但是,您可以使用多个线程同时运行您的请求。您可以使用 Java 中的本机 ExecutorService 来使用线程池方法。我建议您使用 ExecutorCompletionService 来运行您的请求。由于处理时间不受 CPU 限制,而是受网络限制,因此您可能会使用比当前 CPU 更多的线程。

    例如,在我的一些项目中,我使用 10 多个,有时甚至 50 多个线程(在一个线程池中)来同时检索 URL 数据,即使我只有 4 个 CPU 内核。

    【讨论】:

    • 我无法打开与服务器的连接并为每个请求使用相同的连接吗?所以我不必每次都重新连接到服务器然后断开连接
    • 查看此帖的回复:HttpURLConnection 将尽可能重用连接! stackoverflow.com/questions/5459162/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-21
    • 1970-01-01
    • 2019-12-11
    • 2012-06-14
    • 2019-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多