记录一下初次对接webservice的过程。
一定记得找第三方要源码,正常都会有,否则就要开始往下采坑了。。。
对接webservice有三种方式:
第一种,原生,不需要引入jar包:
1.通过wsdl地址生成java代码:可以通过eclipse,直接import然后选择websevice client 输入地址导入即可。也可以下载apache-cxf,通过里面的wsdl2java命令生成,方式很多,但结果无异可以按自己喜欢的方式选择。
2.生成的代码会有两个service,直接new出来调用即可。
第二种,通过apache-axis2:,这个需要引入好几个jar包:
这个是示例代码,仅供参考,
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.xml.namespace.QName;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.java.security.TrustAllTrustManager;
import org.apache.axis2.rpc.client.RPCServiceClient;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.axis2.transport.http.security.SSLProtocolSocketFactory;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
public static void main(String[] args) throws Exception {
RPCServiceClient client = new RPCServiceClient();
Options options = client.getOptions();
int timeOutInMilliSeconds = 3 * 60 * 1000; // Three minutes
options.setProperty(HTTPConstants.SO_TIMEOUT, new Integer(timeOutInMilliSeconds));
options.setProperty(HTTPConstants.CONNECTION_TIMEOUT, new Integer(timeOutInMilliSeconds));
String address = "https://test.bjp2p.com.cn:8443/platformService";
//HTTPS需加下面的几行代码
final SSLContext sslCtx = SSLContext.getInstance("TLS");
sslCtx.init(null, new TrustManager[]{new TrustAllTrustManager()}, null);
options.setProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER, new Protocol("https",
(ProtocolSocketFactory) new SSLProtocolSocketFactory(sslCtx), 8443));
Date beginDate = new Date();
EndpointReference epf = new EndpointReference(address);
options.setTo(epf);
String arg0 = "arg0";
String arg1 = "arg1";
String arg2 = "arg2";
QName qName = new QName("webservice里面的地址(就是打开http://XXX.com?wsdl里面的service地址", "对应的方法名");
Object[] result1 = client.invokeBlocking(qName, new Object[]{arg0, arg1, arg2}, new Class[]{String.class});
}
第三种,直接通过http,但是需要自己拼装soap的字符串,由于没有试过所以不再赘述,有兴趣的可以百度。
我是用的第一种方式对接,当时当中也遇到一个问题,就是https请求时,jdk会默认拦截而且需要你的证书,但是第三方并不需要证书,所以这里请求过不去。百度后的解决方式是设置所有的http请求都不需要验证,但这种方式在有一些需要证书的第三方出现时就会有冲突。目前还没有找到一个合适的解决办法。。