我想获取互联网的图片并插入单词。
我使用此代码。
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;
答案 0 :(得分:35)
我为HttpWebRequest
添加了凭据。
myReq.UseDefaultCredentials = true;
myReq.PreAuthenticate = true;
myReq.Credentials = CredentialCache.DefaultCredentials;
答案 1 :(得分:9)
您是否应该为您的网站提供凭据,而不是传递DefaultCredentials?
像request.Credentials = new NetworkCredential("UserName", "PassWord");
此外,请删除request.UseDefaultCredentials = true; request.PreAuthenticate = true;
答案 2 :(得分: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");
}
}
}