以前调用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调用。