天天看點

記一次最簡單的方法調用webservice服務

調用開放的webservice有以下幾種方式:

方式1:Http可以用來調用webservie服務,也可以抓取網頁資料

方式1:純java(自帶API) jws

方式2:cxf架構

方式3:axis2架構

今天來看看最簡單一直調用方式

// 定義一個請求封包模闆
String xmlTemplate =
        "<?xml version\"1.0\" encoding=\"UTF-8\"?>\n" +
        "<soapenv:Envelope xmlns:ns0=\"http://bea.isprint.com/\"\n" +
            "xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"" +
            "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n" +
            "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
            "<soapenv:Header>\n" +
            "</soapenv:Header>\n" +
            "<soapenv:Body>\n" +
                "<ns0:verifySessionToken xmlns:ns0=\"http://bea.isprint.com/\">\n" +
                    "<sessionToken>%s</sessionToken>\n" +
                    "<csrf>%s</csrf>\n" +
                "</ns0:verifySessionToken>\n" +
            "<soapenv:Body>\n" +
        "</soapenv:Envelope>";

// 使用HttpURLConnection調用
String xmlRequest = String.format(xmlTemplate, sessionToken, String csrf);

OutputStream os = null;
InputStream is = null;
InputStreamReader isreader = null;
String result = null;

try {
    URL url = new URL(ConfigUtils.get(Constant.SSO_SERVER_URL_KEY));
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("SOAPAction", "application/soap+xml");
    conn.setRequestProperty("Content-Type", "application/xml; charset=UTF-8");
    conn.setRequestProperty("Accept", "application/json");
    conn.setConnectTimeout(30000);
    conn.setReadTimeout(30000);
    conn.setDoInput(true);
    conn.setDoOutput(true);

    os = conn.getOutputStream();
    os.write(xmlRequest.getBytes());
    os.flush();

    conn.connect();
    int responseCode = conn.getResponseCode();
    if(200 == responseCode) {
        is = conn.getInputStream();
    } else {
        is = conn.getErrorStream();
    }
    isreader = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isreader);
    StringBuilder sb = new StringBuilder();
    String temp = null;
    while (null != (temp = br.readLine())) {
        sb.append(temp);
    }
    result = sb.toString();
    logger.info(result);
} catch (Exception e) {
    logger.info("通訊失敗");
    e.printStackTrace();
} finally {
    try {
        os.close();
        is.close();
        isreader.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}