Error when use link from Sharepoint with C# ( (401) unauthorized ) - c#

When I upload an image, the sharepoint will give a link corresponding to that image.
I am working on a C # project that analyzes images, and want to use SHarepoint's image link.
But when executing the function to load the image from WebClient's url (), I was blocked by an error.
Error name: "the remote server returned an error (401) unauthorized"
this is image show link in my Sharepoint (the link that I am scanning): https://ibb.co/g9jYHKC
And this is code webclient() I used:
var webClient = new WebClient();
byte[] imageBytes = webClient.DownloadData("http://pmssd78/Animal/birddd.jpg"); //link copy from sharepoint like image show
Looking forward to hearing from everybody soon, thanks

HTTP 401 means unauthorized, which means you aren't authenticated with the resource that you are making the request to. You need to authenticate with the server for it to accept your request.
With the WebClient class, you can do this via the Credentials class member:
//Create a Credential Cache - you'll want this to be defined somewhere appropriate,
//maybe at a global level so other parts of your application can access it
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(new Uri("http://yourSharepointUrl.com"), "Basic", new NetworkCredential("yourUserName", "yourSecuredPassword"));
//Create WebClient, set credentials, perform download
WebClient webClient = new WebClient();
webClient.Credentials = credentialCache.GetCredential(new Uri("http://yourSharepoint.com"),
"Basic");
byte[] imageBytes = webClient.DownloadData("http://pmssd78/Animal/birddd.jpg");
Likely, the Uri used in the credential cache is going to be something along the lines of your URI being used in the .DownloadData signature.

Related

using HTTP HttpWebRequest to extract sharepoint data in c#

I am trying to read a sharepoint site using HttpWebRequest, but the below code throws an exception (403 Forbidden):
HttpWebRequest r = (HttpWebRequest)WebRequest.Create(#"https://myCompany.sharepoint.com/sites/it/abc/ScriptAttest/docs/");
r.Method = "GET";
WebResponse rs = r.GetResponse();
I get the same response if I add
client.Credentials = new NetworkCredential("username", "secret");
(using my domain credentials of course)
or specify default credentials.
However, if I create a browser control (called documentBrowser) and execute the following:
documentBrowser.Navigate(#"https://myCompany.sharepoint.com/sites/it/abc/ScriptAttest/docs/");
I get the data. However, it takes a long time, and I don't really need to display the page. My objective is to parse the html and only pull out certain elements. Additionally, the data comes in stages and the control triggers the DocumentCompleted event after each segment, so I don't really know when the entire page has loaded.
SharePoint Online does not support NetworkCredential. documentBrowser.Navigate in fact use the embed IE browser which may has some SPO related cache, thus it could navigate to the site. If you want to fetch data from SPO, you could use Rest API or CSOM. If you just want to access the site page, you may consider using cookie to get it:
var login = "admin#***.onmicrosoft.com";
var password = "P#ssw0rd";
var siteUrl = "https://***.sharepoint.com/";
var creds = new SharePointOnlineCredentials(login, password);
var auth = creds.AuthenticateAsync(new Uri(siteUrl), true);
var request = (HttpWebRequest)WebRequest.Create(siteUrl);
request.CookieContainer = auth.Result.CookieContainer;
var result = (HttpWebResponse)request.GetResponse();
BR

Generate HTTP request with OAuth access token for Vimeo API in c#

I need to generate an http request to the vimeo api as per step 2 in this page, which is given below.
PUT https://i.cloud.vimeo.com/video/518016424
.... binary data of your file in the body ....
I alredy have an access token for this. Suppose the access token is "qw21we34". How do I generate an http request, with the token in the header and binary data in the body.
I tried using WebClient() class as suggested here, but I cannot find a method to pass the OAuth access token with this type of request. Please note that there are no official libraries for Vimeo api that have this facility. Can anyone help?
For this you can use the WebClient() class. For the authentication, we need the access token from the previous request as well. I got it from my VimeoClient object called vc. That is up to you to figure out.
WebClient wb = new WebClient();
wb.Headers.Add("Authorization","Bearer" +vc.AccessToken);
var file = wb.DownloadData(new Uri(myimageurl));
var asByteArrayContent = wb.UploadData(new Uri(thumbnail_uri), "PUT", file);
var asStringContent = Encoding.UTF8.GetString(asByteArrayContent);
After sending this request, you should get a json response stating the success for asStringContent.

WebClient SSL Single Sign on Proxy

I'm building an AJAX proxy page to pull the information from a SSL Single Sign on Site. Unfortunately I feel like i'm getting stuck. I've tried using webclient and HttpWebRequest but i can't seem to get past the initial page.
I'm catch the a link click action and passing the URL of the link to my proxy page.
$("#Frame").load("/ProxyAjax?url=" + serializedData);
and executing the following code
string redirectUrl = Server.UrlDecode(Request.QueryString["url"]);
Uri myURI = new Uri(redirectUrl);
WebClient wc = new WebClient();
wc.Headers.Add("Cookie", Request.Headers["Cookie"]);
vd.String = wc.DownloadString(redirectUrl);
Have the page I'm calling is executing a redirect and I get stuck somewhere between. Any ideas of how to resolve this?

C# REST WebClient POST Issue

I am trying to upload data to a REST-Service via POST-Method, but for some reasons the server tells me:
System.Net.WebException: The remote server returned an error: NotFound.
I am trying to upload data with this code:
WebClient addserving = new WebClient();
addserving.Credentials = new NetworkCredential(username.Text, passwort.Password);
addserving.Encoding = System.Text.Encoding.GetEncoding("ISO-8859-1");
addserving.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
addserving.UploadStringAsync(new Uri("http://jokr.info/api/v8/diary/add_item.xml&apikey=123456&item_id=1240&serving_id=1566"), "POST");
addserving.UploadStringCompleted += new UploadStringCompletedEventHandler(serving_UploadStringCompleted);
The doc of the API tells me to post like this:
Rate Limit: Yes
HTTP Methods: POST
Authentication: Basic authentication (Username or E-Mail and Password)
Formats: xml
Parameters: format, apikey [GET], activity_id [POST], activity_duration [POST], activity_kj [POST], timestamp [POST] (optional)
Does anyone see what's wrong?
Shouldn't you have a ? before stating query parameters instead of &
http://jokr.info/api/v8/diary/add_item.xml?apikey=123456&item_id=1240&serving_id=1566
You're missing a question mark to mark the beginning of hte parameter collection.
Change
http://jokr.info/api/v8/diary/add_item.xml&apikey=123456&item_id
to
http://jokr.info/api/v8/diary/add_item.xml?apikey=123456&item_id

Cannot handle redirect from HTTP/HTTPS protocols to other dissimilar ones

Basically, I'm trying to grab an EXE from CNet's Download.com
So i created web parser and so far all is going well.
Here is a sample link pulled directly from their site:
http://dw.com.com/redir?edId=3&siteId=4&oId=3001-20_4-10308491&ontId=20_4&spi=e6323e8d83a8b4374d43d519f1bd6757&lop=txt&tag=idl2&pid=10566981&mfgId=6250549&merId=6250549&pguid=PlvcGQoPjAEAAH5rQL0AAABv&destUrl=ftp%3A%2F%2F202.190.201.108%2Fpub%2Fryl2%2Fclient%2Finstaller-ryl2_v1673.exe
Here is the problem: When you attempt to download, it begins with HTTP, then redirects to an FTP site. I have tried .NET's WebClient and HttpWebRequest Objects, and it looks like Neither can support Redirects.
This Code Fails at GetResponse();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://dw.com.com/redir");
WebResponse response = req.GetResponse();
Now, I also tried this:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://dw.com.com/redir");
req.AllowAutoRedirect = false;
WebResponse response = req.GetResponse();
string s = new StreamReader(response.GetResponseStream()).ReadToEnd();
And it does not throw the error anymore, however variable s turns out to be an empty string.
I'm at a loss! Can anyone help out?
You can get the value of the "Location" header from the response.headers, and then create a new FtpWebRequest to download that resource.
in your first code snippet you will be redirected to a link using a different protocol (i.e it's no longer Http as in HttpWebRequest) so it fails du to a malformed http response.
In the second part you're no longer redirected and hence you don't receive a FTP response (which is not malform when interpreted as HTTP response).
You need to acquire FTP link,as ferozo wrote you can do this by getting the value of the header "location", and use a FtpWebRequest to access the file

Categories

Resources