使用 HttpURLConnection 调用 WebService 时的性能调整
我试图调用一个返回太多数据的网络服务,只是为了提取一小部分数据。
所以,我决定不使用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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
connection.getInputStream();
- 等待服务器响应的函数...您无法加快此过程。connection.getInputStream();
- function which wait for server response... you can't speed up this proccess.