简体   繁体   中英

javax.xml.ws.Service fails in constructor because site has username/password

I want to access a web service and this is what the code looks like:

URL url = new URL("http://localhost:8080/sample?ver_=1.0");

QName qname = new QName("http://webservices.sample.com/sample", "sample");

javax.xml.ws.Service service = javax.xml.ws.Service.create(url, qname);

The line that initializes 'service' throws a 401 Unauthorized exception.

If I visit the

http://localhost:8080/sample?ver_=1.0 

using a browser, a window asking for a username and password pops up.

I tried capturing the packets using Wireshark and noticed that the constructor for service sends an HTTP Get to the IP Address but without the credentials.

How do I make sure that the call to HTTP Get by the Service constructor include the username/password?

I already tried putting this before the call but it didn't help

Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
"username",
"password".toCharArray());
}
});

Thanks!

You need to get your service endpoint. Using the endpoint the get requestContext and add the authentication headers, here is the sample code, modify it according to your web services and authentication credentials.

Example example = service .getXXXPort();

Map<String, Object> req_ctx = ((BindingProvider)example).getRequestContext();
req_ctx.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "your web service URL here");

Map<String, List<String>> headers = new HashMap<String, List<String>>();
headers.put("Username", Collections.singletonList("username"));
headers.put("Password", Collections.singletonList("password"));
req_ctx.put(MessageContext.HTTP_REQUEST_HEADERS, headers);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM