1

我正在尝试使用 Httpwebrequest 访问外部实时会议 URL,并收到 401 未经授权的错误。相同的代码在我的本地系统中工作。

代码:

     HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(PostingUrl);
     CredentialCache CredMCCache = new CredentialCache();
        myReq.PreAuthenticate = true;
        CredMCCache.Add(new System.Uri(PostingUrl),"Basic",new    System.Net.NetworkCredential("username","password")
 myReq.Credentials = CredMCCache;
        myReq.KeepAlive = true;
        myReq.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";
        myReq.Accept = "*/*";
        myReq.Headers.Add("Accept-Language", "en-us");
        myReq.Headers.Add("Accept-Encoding", "gzip, deflate");
        WebProxy proxyObject = new WebProxy("proxy url with port", false);
        myReq.Proxy = proxyObject;
        myReq.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
        myReq.Method = "GET";
        HttpWebResponse myResp = null;


            // Get the response from the conference center
            myResp = (HttpWebResponse)myReq.GetResponse();

我在上面的行中收到错误。任何指针都会有所帮助。

4

1 回答 1

0

你为什么要设置代理,例如

myReq.Proxy = 代理对象;

你需要这样做吗?如果您确实要通过公司代理,则不需要设置代理,HttpWebRequest因为它将从 IE 中获取设置(如果有)。

其次,您是否尝试使用基本身份验证与远程服务器进行身份验证?看起来你是,所以使用它来设置标题中的身份验证详细信息

string authInfo = userName + ":" + userPassword;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
myReq.Headers["Authorization"] = "Basic " + authInfo;
于 2012-08-01T15:27:19.420 回答