5

如何通過基本的http認證訪問web服務?我正在使用內置web服務客戶端功能的netbeans。但是,當我嘗試訪問Web服務時,出現401 auth失敗錯誤消息的異常。Netbeans Basic Http Auth Jax-WS

如何傳遞正確的用戶名和密碼?

謝謝!

回答

4

您可以使用BindingProvider或WSBindingProvider類通過基本的http認證來訪問Web服務。代碼如下: 代碼如下。

XxxService service = new XxxService(); 
Xxx port = service.getXxxPort(); 

Map<String, Object> reqContext = ((BindingProvider)port).getRequestContext(); 
reqContext.put(BindingProvider.USERNAME_PROPERTY, "username"); 
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "password"); 
+2

如果WSDL本身不受基本Http身份驗證的保護 – snowflake 2010-03-19 08:39:31

+0

爲什麼它不適用於我?我確切地說'AImpl aImplPort = new AImplService()。getAImplPort(); BindingProvider prov =(BindingProvider)aImplPort; prov.getRequestContext()。put(BindingProvider.USERNAME_PROPERTY,「fred」); ()。(putdingProvider.PASSWORD_PROPERTY,「fred」); String b = aImplPort.b(); System.out.println(b);'不是發送期望的授權http頭部 – 2012-05-19 06:41:43

3

您也可以提供自己的驗證器。這樣即使WDSL本身受到基本的HTTP認證保護,它也能工作。

@WebServiceRef(wsdlLocation = "https://laka/sito?wsdl") 
static XxxService service; 

public static void main(String[] args) { 

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

    service = new XxxService(); 
    Xxx port = service.getXxxPort(); 

    // invoke webservice and print response 
    XxxResponse resp = port.foo(); 
    System.out.println(resp.toString()); 

} 
+0

不知道java包含了這個特性。很有幫助。謝謝! – gruenewa 2012-03-07 11:25:33

+0

它爲什麼適用於我和'reqContext.put(BindingProvider.USERNAME_PROPERTY,「username」); '方法不是和我的java版本有關嗎? – 2012-05-19 06:44:58