天天看点

WebService 401 unauthorized 授权认证错误

使用Web Service时,有时服务器需要client客户端进行授权验证,这时需要在client端提供用户名和密码,否则抛出401 unauthorized未授权错误。对于这个问题,只要加上用户名、密码即可:

<span style="font-size:14px;">HttpTransportProperties.Authenticator basicauth = new HttpTransportProperties.Authenticator();   
basicauth.setUsername("username");  //服务器访问用户名 
basicauth.setPassword("password"); //服务器访问密码
options.setProperty(HTTPConstants.AUTHENTICATE, basicauth);</span>
           

详细代码:

<span style="font-size:14px;">//Service的地址
String serviceName = "http://192.168.0.96/sipxconfig/services/HelloService?wsdl";
//命名空间,wsdl文件中definitions标签下的 targetNamespace的值
String namespace = "http://www.sipfoundry.org/2007/08/21/ConfigService";
//方法名,即要调用的方法,这里不详细解析,请参考:http://clq9761.iteye.com/blog/976029
String methodName = "HelloService";

Object[] methodArgs = new Object[] {  };
Class[] returnTypes = new Class[] { Object.class };
RPCServiceClient serviceClient = new RPCServiceClient();
Options options = serviceClient.getOptions();
//设置密码
HttpTransportProperties.Authenticator basicauth = new HttpTransportProperties.Authenticator();   
basicauth.setUsername("username");  //服务器访问用户名 
basicauth.setPassword("password"); //服务器访问密码
options.setProperty(HTTPConstants.AUTHENTICATE, basicauth);
   
EndpointReference targetEPR = new EndpointReference(serviceName);
options.setTo(targetEPR);
  
//options.setAction("urn:"+methodName);
QName op= new QName(namespace,methodName);
Object[] response = serviceClient.invokeBlocking(op, methodArgs,returnTypes);
//返回结果
String result = (String) response[0];</span>
           

另外,如果是用wsdl2java.bat或eclipse插件生成代码的话,只需在生成相应的Stub类中的ConfigImplServiceStub的方法了添加下面几行代码即可:

<span style="font-size:14px;">HttpTransportProperties.Authenticator basicauth = new HttpTransportProperties.Authenticator();   
basicauth.setUsername("username");   
basicauth.setPassword("password");
_serviceClient.getOptions().setProperty(HTTPConstants.AUTHENTICATE, basicauth);</span>
           

其中,_serviceClient为org.apache.axis2.client.ServiceClient的实例。以上的两种方法起始原理都一样的,属于NTLM认证,请参考:http://minjiaren.iteye.com/blog/432338

本文涉及到Axis2,详细配置和使用请参考:http://clq9761.iteye.com/blog/976029

博主寄语:写博客时,起一个长的博客名,是一种美德。尽量在博客名里写上与博文相关的字眼,这样可以增加读者搜索到博客的几率,在增加人气的同时也把你的智慧成果分享给他人。

尊重原著,转载请注明出处。