我得到了一个用 Java 编写的 Web 服务,但我无法对其进行任何更改。它要求用户使用基本身份验证进行身份验证才能访问任何方法。在 .NET 中与此服务交互的建议方法是使用安装了 WSE 3.0 的 Visual Studio 2005。
这是一个问题,因为该项目已经在使用 Visual Studio 2008(面向 .NET 2.0)。我可以在 VS2005 中做到这一点,但是我不想将项目绑定(bind)到 VS2005 或通过在 VS2005 中创建程序集并将其包含在 VS2008 解决方案中来完成(无论如何,这基本上将项目与 2005 联系起来,以便将来对程序集进行任何更改)。我认为这些选项中的任何一个都会迫使新开发人员安装 WSE 3.0 并阻止项目在 future 使用 2008 和 .NET 3.5 中的功能……也就是说,我真的相信使用 WCF是要走的路。
我一直在研究为此使用 WCF,但是我不确定如何让 WCF 服务了解它需要与每个请求一起发送身份验证 header 。当我尝试对 Web 服务执行任何操作时出现 401 错误。
这就是我的代码的样子:
WebHttpBinding webBinding = new WebHttpBinding();
ChannelFactory<MyService> factory =
new ChannelFactory<MyService>(webBinding, new EndpointAddress("http://127.0.0.1:80/Service/Service/"));
factory.Endpoint.Behaviors.Add(new WebHttpBehavior());
factory.Credentials.UserName.UserName = "username";
factory.Credentials.UserName.Password = "password";
MyService proxy = factory.CreateChannel();
proxy.postSubmission(_postSubmission);
这将运行并抛出以下异常:
The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'Basic realm=realm'.
这有一个内部异常(exception):
The remote server returned an error: (401) Unauthorized.
任何关于可能导致此问题的想法将不胜感激。
最佳答案
第一个问题:这是您尝试调用的 SOAP 还是基于 REST 的 Java 服务?
现在,通过“webHttpBinding”,您正在使用基于 REST 的方法。如果 Java 服务是 SOAP 服务,那么您需要将绑定(bind)更改为“basicHttpBinding”。
中频这是一个基于 SOAP 的服务,你应该试试这个:
BasicHttpBinding binding = new BasicHttpBinding();
binding.SendTimeout = TimeSpan.FromSeconds(25);
binding.Security.Mode = BasicHttpSecurityMode.Transport;
binding.Security.Transport.ClientCredentialType =
HttpClientCredentialType.Basic;
EndpointAddress address = new EndpointAddress(your-url-here);
ChannelFactory<MyService> factory =
new ChannelFactory<MyService>(binding, address);
MyService proxy = factory.CreateChannel();
proxy.ClientCredentials.UserName.UserName = "username";
proxy.ClientCredentials.UserName.Password = "password";
我已经将它与各种 Web 服务一起使用,并且它在大多数情况下都能正常工作。
如果这不起作用,您将不得不了解更多关于 Java Web 服务期望什么以及如何将相关信息发送给它的信息。
马克
关于wcf - 无法使用 WCF 调用具有基本身份验证的 Web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1365163/