Java使用HttpUrlConnection調用webService(wsdl)

首先須要下載工具https://pan.baidu.com/s/1XQ-VubxcPFoqwGm7wierHgjava

下載成功後解壓打開exe程序,在wsdl endpoint中輸入你wsdl的地址,點擊get,等待一小會後會跳到invoke標籤下的界面web

點擊某個方法,例如上圖的login,能夠看到右邊有userName和password兩個參數須要填入,點擊填寫完後點invoke,此時下面的output就把result顯示出來了,這時候點擊Request/Response標籤,能夠看到request的屬性、request請求體及response返回內容,這些信息等等代碼裏會用到,下面開始是Java調用方法。服務器

 

/**
     * soap調用webService
     */
    public static String sendSoapPost(String url,String xml,String contentType,String soapAction){
        HttpURLConnection conn = null;
        OutputStream out = null;
        String returnXml = "";
        try{
            conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setRequestProperty("Content-Type",contentType);
            if(null != soapAction){
                conn.setRequestProperty("SOAPAction",soapAction);
            }
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(5000);
            conn.setDoOutput(true); // 向服務器發送數據
            conn.setDoInput(true);  // 獲取服務端的響應
            conn.connect();
            out = conn.getOutputStream();
            out.write(xml.getBytes("UTF-8"));
            out.flush();
            out.close();
            int code = conn.getResponseCode();
            String tempString = null;
            StringBuffer sb = new StringBuffer();
            BufferedReader bufferedReader = null;
            if(code == conn.HTTP_OK){
                bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
            }else{
                bufferedReader = new BufferedReader(new InputStreamReader(conn.getErrorStream(),"UTF-8"));
            }
            while((tempString = bufferedReader.readLine()) != null){
                sb.append(tempString);
            }
            if(null != bufferedReader){
                bufferedReader.close();
            }
            //響應報文
            returnXml = sb.toString();
        }catch (Exception e){
            e.printStackTrace();
        }
        return returnXml;
    }

  這個方法四個參數,其中xml參數須要把剛剛獲得的請求體複製過來後進行修改,對應你要調用的方法和參數等。url、contentType,soapAction則對應剛剛獲得的request屬性裏的屬性名同樣的值,調用方法運行就會獲得響應結果了。app

相關文章
相關標籤/搜索