由於業務上的需要,需要訪問第三方提供的webservice介面,但由於公司做了對外訪問的限制,不設定代理是不能外網的,如果使用http設定代理訪問外網還是比較容易的,但使用cxf有點不知道從哪裡入手。網上也有一些零散的資訊,現在我整理一下提供參考。
1、JaxWsProxyFactoryBean設定代理
import org.apache.cxf.configuration.security.ProxyAuthorizationPolicy; import org.apache.cxf.endpoint.Client; import org.apache.cxf.frontend.ClientProxy; import org.apache.cxf.jaxws.JaxWsProxyFactoryBean; import org.apache.cxf.transport.http.HTTPConduit; import org.apache.cxf.transports.http.configuration.HTTPClientPolicy; public class TeacherService { public String getStudents(StudentCard card){ JaxWsProxyFactoryBean factoryBean = new JaxWsProxyFactoryBean(); factoryBean.setServiceClass(TeacherWebService.class); factoryBean.setAddress("http://xxx.xxx.xxx.xxx/webservice?wsdl"); TeacherWebService tService = (TeacherWebService )factoryBean.create(); Client client = ClientProxy.getClient(tService); HTTPConduit http = (HTTPConduit) client.getConduit(); HTTPClientPolicy hcp = new HTTPClientPolicy(); hcp.setProxyServer(proxyHost); hcp.setProxyServerPort(proxyport); http.setClient(hcp); ProxyAuthorizationPolicy proxyAuthorization = new ProxyAuthorizationPolicy(); proxyAuthorization.setUserName(proxyUsername); proxyAuthorization.setPassword(proxyPassword); http.setProxyAuthorization(proxyAuthorization); String res = tService.getStudents(card); return res; } }
2、使用JaxWsDynamicClientFactory設定代理
import java.net.Authenticator; import java.net.PasswordAuthentication; import javax.xml.namespace.QName; import org.apache.cxf.endpoint.Client; import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory; import com.thoughtworks.xstream.XStream; public class TeacherService { public String getStudents(StudentCard card)throws Exception{ System.setProperty("http.proxyHost","http.proxy.host"); System.setProperty("http.proxyPort", "http.proxy.port"); Authenticator.setDefault(new MyAuthenticator("username", "password"))); JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance(); //url為呼叫webService的wsdl地址 Client client = dcf.createClient("http://xxx.xxxx.xxx.xxx:8080/webservice?wsdl"); //namespace是名稱空間,methodName是方法名 QName name=new QName("http://www.xxxx.com","getStudents"); XStream xstream = new XStream(new XppDriver(new XmlFriendlyNameCoder("_-", "_"))); Object[] objects = client.invoke(name,xstream.toXML(card)); String res = ""; if(objects != null && objects.length != 0){ res = objects[0].toString(); } return res; }
static class MyAuthenticator extends Authenticator {
private String username, password;
public MyAuthenticator(String username, String password) {
this.username = username;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
}
}
}