儘管您可能已經解決了您的問題,但我想提供一個示例實現,如果其他人有一些用處。
服務器:
javax.xml.ws.Endpoint serverEndpoint = Endpoint.create(new MyService());
com.sun.net.httpserver.HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
com.sun.net.httpserver.HttpContext httpContext = server.createContext("/myservice");
server.start();
AuthenticatorServer authenticatorServer = new AuthenticatorServer("myRealm", "myName", "myPwd");
httpContext.setAuthenticator(authenticatorServer);
serverEndpoint.publish(httpContext);
其中AuthenticatorServer是:
private static class AuthenticatorServer extends com.sun.net.httpserver.BasicAuthenticator {
private final String user;
private final String pwd;
public AuthenticatorServer(String realm, String user, String pwd) {
super(realm);
this.user = user;
this.pwd = pwd;
}
@Override
public boolean checkCredentials(String userNameInput, String passwordInput) {
return StringUtils.equals(user, userNameInput) && StringUtils.equals(pwd, passwordInput);
}
}
而且在客戶端:
AuthenticatorClient authenticatorClient = new AuthenticatorClient("myName", "myPwd");
Authenticator.setDefault(authenticatorClient);
javax.xml.namespace.QName qName = new QName(namespaceURI, WS_SERVICE_NAME);
java.net.URL wsdlAddress = new URL(namespaceURI + WS_SERVICE_NAME + "?wsdl");
MyService service =(Service.create(wsdlAddress, qName)).getPort(MyService.class);
其中AuthenticatorClient是:
private static class AuthenticatorClient extends java.net.Authenticator {
private final String user;
private final String pwd;
public AuthenticatorClient(String user, String pwd) {
this.user = user;
this.pwd = pwd;
}
@Override
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication(user, pwd == null ? null : pwd.toCharArray()));
}
}