使用 HttpURLConnection 调用 WebService 时的性能调整

发布于 2024-12-25 15:29:18 字数 988 浏览 1 评论 0原文

我试图调用一个返回太多数据的网络服务,只是为了提取一小部分数据。

所以,我决定不使用Java生成的标准Client。

我使用以下代码进行连接:

HttpURLConnection connection;
byte[] requestData = .....
URL url = new URL(wsUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "text/xml");
connection.setRequestProperty("Content-Length", String.valueOf(requestData.length));
connection.connect();
OutputStream connOs = connection.getOutputStream();
connOs.write(requestData);
connOs.close(); 
InputStream is = connection.getInputStream();   // <<< THIS IS THE MOST TIME CONSUMING, it takes about 70 ms
byte[] rply = stream2Bytes(is);
is.close();
connection.disconnect();

大部分时间消耗在调用 connection.getInputStream(); 上,大约需要 70 毫秒。

我正在尝试设置许多请求标头来减少这个时间,但无法达到。

据我了解,HttpUrlConnection 使用 HTTP1.1 协议,默认使用 Connection=KEEP-ALIVE 标头,以便重用底层 TCP 连接。

I am trying to call a webservice that return too much data just to extract a small piece of data.

So, I decided not to use the standard Client which is generated by Java.

I use the following code to do the connection:

HttpURLConnection connection;
byte[] requestData = .....
URL url = new URL(wsUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "text/xml");
connection.setRequestProperty("Content-Length", String.valueOf(requestData.length));
connection.connect();
OutputStream connOs = connection.getOutputStream();
connOs.write(requestData);
connOs.close(); 
InputStream is = connection.getInputStream();   // <<< THIS IS THE MOST TIME CONSUMING, it takes about 70 ms
byte[] rply = stream2Bytes(is);
is.close();
connection.disconnect();

The most time is consumed in the call to connection.getInputStream(); which it takes about 70ms.

I am trying setting many request headers to reduce this time but cannot reach.

My understanding it that the HttpUrlConnection uses HTTP1.1 protocol that uses Connection=KEEP-ALIVE header by default so that the underlying TCP connection is reused.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

请爱~陌生人 2025-01-01 15:29:18

connection.getInputStream(); - 等待服务器响应的函数...您无法加快此过程。

connection.getInputStream(); - function which wait for server response... you can't speed up this proccess.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文