错误:远程服务器返回错误:(401)未经授权

30

我想从互联网上获取图片并插入到Word文档中。

我使用了这段代码。

MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;
System.Net.WebRequest request = 
    System.Net.HttpWebRequest.Create("http://spsdev2:1009");

System.Net.WebResponse response = request.GetResponse();
ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);
//Send an HTTP request and get the image at the URL as an HTTP response
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(fileName);
WebResponse myResp = myReq.GetResponse();

//Get a stream from the webresponse
Stream stream = myResp.GetResponseStream();

我在 myReq.GetResponse(); 处遇到了错误。

错误信息为:远程服务器返回错误:(401) 未经授权。

编辑

这段代码对我有效 :)

myReq.UseDefaultCredentials = true;

myReq.PreAuthenticate = true;

myReq.Credentials = CredentialCache.DefaultCredentials;

这个答案在另一个帖子中对我很有用。 - RBT
3个回答

42

我为 HttpWebRequest 添加了凭证。

myReq.UseDefaultCredentials = true;
myReq.PreAuthenticate = true;
myReq.Credentials = CredentialCache.DefaultCredentials;

9

你应该提供你网站的凭据,而不是传递默认凭据。

可以使用类似于 request.Credentials = new NetworkCredential("用户名", "密码"); 这样的方式。

另外,移除request.UseDefaultCredentials = true; request.PreAuthenticate = true;


你是否更改了用户名和密码,以便实际访问您的网站? - Dante
2
你能否删除以下代码行吗? request.UseDefaultCredentials = true; request.PreAuthenticate = true; - Dante

0

这些答案确实有所帮助,但我认为一个完整的实现将会对很多人有所帮助。

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace Dom
{
    class Dom
    {
        public static string make_Sting_From_Dom(string reportname)
        {
            try
            {
                WebClient client = new WebClient();
                client.Credentials = CredentialCache.DefaultCredentials;
                // Retrieve resource as a stream               
                Stream data = client.OpenRead(new Uri(reportname.Trim()));
                // Retrieve the text
                StreamReader reader = new StreamReader(data);
                string htmlContent = reader.ReadToEnd();
                string mtch = "TILDE";
                bool b = htmlContent.Contains(mtch);

                if (b)
                {
                    int index = htmlContent.IndexOf(mtch);
                    if (index >= 0)
                        Console.WriteLine("'{0} begins at character position {1}",
                        mtch, index + 1);
                }
                // Cleanup
                data.Close();
                reader.Close();
                return htmlContent;
            }
            catch (Exception)
            {
                throw;
            }
        }

        static void Main(string[] args)
        {
            make_Sting_From_Dom("https://www.w3.org/TR/PNG/iso_8859-1.txt");
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接