动态的WebService 直接调用其他的WebService项目 完成
历时4天的时间 查资料 看代码 测试等等 弄得我头昏脑涨的……
不过经理给我一个月的时间 研究 我只用了四天 剩下的时间就可以低调的玩了 呵呵呵呵…………
嗯哼 低调!~~ 最难的部分已经完成 下面还需要麻烦的写代码呢……呵呵呵呵…………
好啦 开始说主题
虽然说是动态加载WebService的WebService 但实质并不是WebService 而且测试我只测了自己公司两台机器上的WebService 至于别的好不好用 我就不知道了
其实WebService的实质就是传递XML
在《通过前台jquery调用本地WebService》一、二 中 也介绍了很多关于这个XML的结构
重点也说过了 但是根据同源策略 也就是说 通过jquery调用WebService只能调用自己电脑上的 即便是同一个网段里的两台电脑 都不可以相互调用
原因是XMLHttpRequest跨域问题 即刚才提到的同源策略
其实WebService只传递SOAP体是不可以的 还需要Request头信息中带有SOAPAction 和 Respouse头信息中带有 Access-Control-Allow-Origin即CORS
前台jquery调用WebService 我只能生成SOAPAction 并不能认证CORS 所以 只能在本地调用 并不能调用除本机之外的机器
那么首先 我想到的是 在服务器上设置Respouse头信息 可是查了一整天也没有头绪 完全不是java能用得上的 不是C# 就是.NET
而且 即使得到在服务器上设置Respouse头信息的方法 也需要再重新写一个特定的WebService供客户端调用
于是 再继续查询资料 即将放弃的时候 查到了URL Connection方式
在此留下原文网址:http://www.cnblogs.com/siqi/archive/2013/12/15/3475222.html
(此文章写了四种调用WebService的方式)
其中URL Connection方式调用的代码 经过测试 是错误的……其他方式均未测试
通过两天的查询积累
在此写下新的URL Connection方式
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class CallWBSTest {
public void callWbs(String url,String nameSpace, String method ,String parameter , String value) throws Exception{
URL wsUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) wsUrl.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
conn.setRequestProperty("SOAPAction", nameSpace+"/"+method);//原文中不存在此行 所以错误
OutputStream os = conn.getOutputStream();
//SOAP体的拼接
String soap = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
" <soap:Body> " +
" <"+method+" xmlns=\""+nameSpace+"\">" +
" <"+parameter+">"+value+"</"+parameter+">" +
" </"+method+">" +
" </soap:Body>" +
"</soap:Envelope>";
os.write(soap.getBytes());
InputStream is = conn.getInputStream();
byte[] b = new byte[1024];
int len = 0;
String s = "";
while((len = is.read(b)) != -1){
String ss = new String(b,0,len,"UTF-8");
s += ss;
System.out.print(s);
}
is.close();
os.close();
conn.disconnect();
}
public static void main(String[] args) {
CallWBSTest cwt = new CallWBSTest();
String url = url; //WebService的Url
String nameSpace = nameSpace; //WebService的命名空间
String method = method; //WebService的方法
String parameter = parameter; //WebService的方法参数
String value = value; //WebService的参数值
try {
cwt.callWbs(url, nameSpace, method, parameter, value);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
此方法就可以返回一个XML 然后手动解析XML 即可得到最终结果!~