我消費使用HttpURLConnection的歷時60秒返回響應網絡服務,但是當我用捲曲(命令行)與相同參數相同的操作,然後只用了20 - 25秒返回響應。curl命令行VS HttpURLConnection的API業務呼叫響應時間差異
通過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秒)才能返回響應,但是當我ru時n在同一臺服務器上與獨立java程序相同的java代碼,然後在20秒內返回響應。完全相同的代碼。現在,我不明白爲什麼相同的代碼在從Web應用程序執行時需要更長的時間。
您還可以顯示您如何閱讀回覆?也許有事發生在那裏。 –
@adhesivee的InputStream xmlResponse串轉換需要幾乎1秒到2秒。 – Santosh