【发布时间】:2016-03-22 10:43:44
【问题描述】:
我正在使用使用 HttpURLConnection 的 Web 服务,它需要 60 秒才能返回响应,但是当我使用 CURL(命令行)进行具有相同参数的相同操作时,只需要 20 - 25 秒即可返回响应。
通过 HttpURLConnection 调用 API 服务时可能出现什么问题,因为返回响应需要更长的时间。
HttpURLConnection API 调用代码:
`
url = new URL(this._serviceURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
connection.setRequestProperty("Accept", "application/xml;");
connection.setRequestProperty("SOAPAction", "http://www.xxtest.com/Request");
connection.setDoInput(true);
connection.setDoOutput(true);
// Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(xmlRequest);
wr.flush();
wr.close();
// Get Response
responseCode = connection.getResponseCode();
String xmlResponse = "";
if (responseCode == HttpURLConnection.HTTP_OK) { // success
is = connection.getInputStream();
xmlResponse = IOUtils.toString(is);
// Decode base64 and Decompress
final GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(Base64.decodeBase64(xmlResponse.getBytes())));
xmlResponse = IOUtils.toString(gzipInputStream);
}`
CURL 命令:
curl -XPOST -H "Content-type: text/xml" -H "SOAPAction: http://www.xxtest.com/Request" -H "Accept: application/xml;" -d @request_soap.xml 'http://www.xxtest.com/xmlservices.asmx' > response.xml
更新: 上面提到的 HttpURLConnection API 调用 java 代码 - 当从 Web 应用程序(Tomcat)执行时,返回响应需要更长的时间(60 秒),但是当我在同一台服务器上运行与独立 java 程序相同的 java 代码时,它会返回响应在 20 秒内。完全相同的代码。现在,我不明白为什么从 Web 应用程序执行相同的代码需要更长的时间。
【问题讨论】:
-
您能否也展示一下您是如何阅读回复的?也许那里正在发生一些事情。
-
@adhesivee InputStream 到 xmlResponse 字符串转换几乎不需要 1 秒到 2 秒。
标签: java performance web-services curl httpconnection