简体   繁体   中英

Error :The remote server returned an error: (401) Unauthorized

I want get picture of internet and insert into word .

I use this code .

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();

I get error in myReq.GetResponse();

Error :The remote server returned an error: (401) Unauthorized.

Edit

This code work for me :)

myReq.UseDefaultCredentials = true;

myReq.PreAuthenticate = true;

myReq.Credentials = CredentialCache.DefaultCredentials;

I add credentials for HttpWebRequest .

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

Shouldn't you be providing the credentials for your site, instead of passing the DefaultCredentials?

Something like request.Credentials = new NetworkCredential("UserName", "PassWord");

Also, remove request.UseDefaultCredentials = true; request.PreAuthenticate = true; request.UseDefaultCredentials = true; request.PreAuthenticate = true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM