Java: 討人厭的SOAP Web Service;使用SoapUI解決

我們有個和第三方系統以Web Service同步的作業,使用傳統的SOAP溝通,不知為何在送出request後總會停頓十多秒才會接到回應,這個問題困擾許久,一直無法找到解決方法。

IE 11除錯追蹤

我們以IE 11的F12除錯偵測的狀況如下:

  1. 在呼叫Web Service之前按〔F12〕→【網路】並啟動其追蹤功能。 IE11-Network
  2. 送出request後會記錄網路傳輸狀況。 send request
  3. 按【詳細資訊】可以查看要求與回應的詳細內容。 Newtwork detail

其實這些追蹤只是證實每次都會等待才會接到回應,延遲狀態依舊無法改善。最後只好修改程式,放棄標準的SOAP寫法改用更低階些的java.net.URL,改寫步驟是:

1. 下載並安裝SoapUI

SoapUI是一套開源的Web Service測試應用程式,透過SoapUI我們就能擷取到傳輸過程中的內容,再用java.net.URL來傳送這些內容。

2. 執行SoapUI

首先建立新的request並指定Web Service的WSDL網址,再將request的XML內容存入剪貼簿,這個內容就是我們要使用的request內容。 SoapUI

3. 撰寫Java程式

使用java.net.URL叫用Web Service的寫法示範如下:

URL baseURL = new URL(urlAddress);
    con = (HttpURLConnection) baseURL.openConnection();
    con.setDoInput(true);
    con.setDoOutput(true);
    con.setUseCaches(false);
    //  發送請求参数;要換成由SoapUI取到的request內容
    String soap = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://第三方WebService網址/\">" +
        "   <soapenv:Header/>" +
        "   <soapenv:Body>" +
        "      <ws:process>" +
        "         <arg0>" + params + "</arg0>" +
        "      </ws:process>" +
        "   </soapenv:Body>" +
        "</soapenv:Envelope>";
    System.out.println("soap:"+soap);
    con.setRequestMethod("POST");
    con.setRequestProperty("Accept", "application/soap+xml");
    con.setRequestProperty("Content-length", String.valueOf(soap.length()));
    con.setRequestProperty("Content-Type", "application/soap+xml;charset=UTF-8");

    dataOutput = new DataOutputStream(con.getOutputStream());
    dataOutput.write(soap.getBytes("UTF-8"));
    dataOutput.flush();
    dataOutput.close();

    // 取出回應
    dataOutput = null;
    int code = con.getResponseCode();
    System.out.println("Code=" + code);
    System.out.println("resp msg=" + con.getResponseMessage() + "<hr>");

    StringBuilder result = new StringBuilder();

    InputStream is = con.getInputStream();

    reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
    String line;

    while ((line = reader.readLine()) != null) {
      result.append(line);
    }

    String _sResponse = result.toString().trim();
    System.out.println("response:"+_sResponse);

測試後連線速度大幅提升,停頓狀況消失了。至於造成遲延的原因,推測是對方AP Server的版本比較舊的原因,也有同事提出或許是IPv6的問題,不過既然問題解決了就沒有再深入探討的興致了。

##

您可能也會有興趣的類似文章

簡睿

服務於軟體業的資訊老兵。興趣廣泛,學習力佳,樂於分享所知所學。

您可能也會喜歡…

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *