首页 > 代码库 > C#调用Java的WebService时添加身法认证信息的方法

C#调用Java的WebService时添加身法认证信息的方法

Java生成的WebService要求在调用时在http的header里必须带上Authorization:Basic xxxxxxxxxxxxxxx的认证信息

因为是在添加Web Reference后直接调用服务,所以就要重写服务类,重写服务类的GetWebRequest方法,示例代码如下

public class MyService : xxx服务类    {        public MyService(string url)        {            Url = url;        }        protected override WebRequest GetWebRequest(Uri uri)        {            HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(uri);            if (PreAuthenticate)//使用时,必须设置服务类的PreAuthenticate属性为true并设置Credentials属性            {                NetworkCredential networkcredential = base.Credentials.GetCredential(uri, "Basic");                if (networkcredential != null)                {                    Byte[] credentialBuffer = new UTF8Encoding().GetBytes(networkcredential.UserName + ":" + networkcredential.Password);                    request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(credentialBuffer);                }                else                    throw new ApplicationException("No network credentials");            }            return request;        }    }

参考信息:

  http://stackoverflow.com/questions/20495105/basic-authentication-in-php-webservice-with-c/20517700#20517700

  http://stackoverflow.com/questions/897782/how-to-add-custom-http-header-for-c-sharp-web-service-client-consuming-axis-1-4/1712795#1712795

C#调用Java的WebService时添加身法认证信息的方法