由于業(yè)務(wù)上的需要,需要訪問(wèn)第三方提供的webservice接口,但由于公司做了對(duì)外訪問(wèn)的限制,不設(shè)置代理是不能外網(wǎng)的,如果使用http設(shè)置代理訪問(wèn)外網(wǎng)還是比較容易的,但使用cxf有點(diǎn)不知道從哪里入手。網(wǎng)上也有一些零散的信息,現(xiàn)在我整理一下提供參考。
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; }}
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為調(diào)用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());
}
}
}
聯(lián)系客服