加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

WebService 401 unauthorized 授权认证错误

发布时间:2020-12-16 23:35:35 所属栏目:安全 来源:网络整理
导读:使用Web Service时,有时服务器需要client客户端进行授权验证,这时需要在client端提供用户名和密码,否则抛出401 unauthorized未授权错误。对于这个问题,只要加上用户名、密码即可: span style="font-size:14px;"HttpTransportProperties.Authenticator b

使用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


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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读