28

我想获取互联网图片并插入到 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;
4

3 回答 3

41

我为HttpWebRequest.

myReq.UseDefaultCredentials = true;
myReq.PreAuthenticate = true;
myReq.Credentials = CredentialCache.DefaultCredentials;
于 2012-04-19T05:20:29.577 回答
9

您不应该为您的站点提供凭据,而不是传递 DefaultCredentials 吗?

就像是request.Credentials = new NetworkCredential("UserName", "PassWord");

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

于 2012-04-18T08:48:39.100 回答
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");
        }
    }
}
于 2019-10-07T19:16:00.360 回答