我在多个线程上运行以下方法:
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请求是否并行处理?以这种方式发出请求会阻止其他线程发送请求,直到第一个响应到达吗?
答案 0 :(得分:1)
可以从不同的线程调用该方法。没有共享变量存在,因此没有并发问题。但是,您可以通过使用连接池(套接字连接)来重用连接以及更快的响应来优化该过程。 无法控制套接字,最终可能会导致时间响应变慢。当然我们正在讨论打开套接字连接以及服务器保持套接字打开的可能性(Keep-Alive标头)