首页 文章

并发http请求

提问于
浏览
1

我在多个线程上运行以下方法:

private JSONObject jsonFromUrl(String requestUrl)  {
    try {
        URLConnection connection = new URL(requestUrl).openConnection();
        connection.setRequestProperty("Accept-Charset", charset);
        InputStream response = connection.getInputStream();
        JSONParser jsonParser = new JSONParser();
        return  (JSONObject)jsonParser.parse(
                new InputStreamReader(response,charset));
    } catch (Exception e) {
        Logger.error("Exception while sending request: " + requestUrl + " error: " + e);
        e.printStackTrace();
        return new JSONObject();
    }
}

HTTP请求是否并行处理?以这种方式发出请求会阻止其他线程发送请求,直到第一个响应到达为止?

1 回答

  • 1

    可以从不同的线程调用该方法 . 没有共享变量存在,因此没有并发问题 . 但是,您可以通过 Build 连接池(套接字连接)来重用连接以及更快的响应来优化流程 . 无法控制套接字,最终可能会导致响应时间变慢 . 当然我们正在讨论打开套接字连接以及服务器保持套接字打开的可能性(Keep-Alive标头)

相关问题