以前調用webservice一般使用axis、axis2先生成java類後,直接引用,多方便。但是有的webservice接口非常的函數,生成的java類非常多,有沒有一種非常簡化的方法。
axis2有不生成類直接調用的方法,但是QName不容易找,每次查N久不到。有的反饋,使用CXF調用一樣方便,但CXF還要使用maven下載jar,而這裏是jdk自帶的^_^.....。
找到一個方便的方法,就是調用HttpURLConnection或HttpsURLConnection直接調用。先在soap查看接口,然後直接把數據傳過來,可以使用postman測試。如果測試成功,正常就可以使用HttpURLConnection調用了。
public static String HttpSendSoapPost(String strurl,String xml){
HttpURLConnection connection = null;
InputStream is = null;
BufferedReader br = null;
String result = null;// 返回結果字符串
OutputStream out = null;
Date d1 = new Date();
try {
// 創建遠程url連接對象
URL url = new URL(strurl);
// 通過遠程url連接對象打開一個連接,強轉成httpURLConnection類
connection = (HttpURLConnection) url.openConnection();
// 設置連接方式:GET,POST
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "text/xml;charset=utf-8");
//這裏必須要寫,否則出錯,根據自己的要求寫,默認爲空
connection.setRequestProperty("SOAPAction", "");
// 設置連接主機服務器的超時時間:15000毫秒
connection.setConnectTimeout(15000);
// 設置讀取遠程返回的數據時間:60000毫秒
connection.setReadTimeout(60000);
// 發送請求
connection.connect();
out = connection.getOutputStream(); // 獲取輸出流對象
connection.getOutputStream().write(xml.getBytes("UTF-8")); // 將要提交服務器的SOAP請求字符流寫入輸出流
out.flush();
out.close();
System.out.println(connection.getResponseCode());
// 通過connection連接,獲取輸入流
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
// 封裝輸入流is,並指定字符集
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
// 存放數據
StringBuffer sbf = new StringBuffer();
String temp = null;
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = sbf.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 關閉資源
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
connection.disconnect();// 關閉遠程連接
}
Date d2 = new Date();
System.out.println(d2.getTime() - d1.getTime());
System.out.println("****** END ********");
//System.out.println();
return result;
}
這種調用webservice個人使用起來非常方便,這個不僅可以在原生的java開發使用,還可以在domino調用。