cxf设置代理访问webservice接口

时间:2022-01-04 16:16:26

  由于业务上的需要,需要访问第三方提供的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());
    }
  }

}