'C# How to launch Chrome and make it perform a web request having Basic Authentication
I'm trying to write C# code that launches chrome.exe to a specific web page, but my requirements involve opening a page that needs Basic Authentication. I am told to provide the Basic Authentication in the request header, and not in the URL. The C# code below launches chrome.exe:
Process proc = new Process();
proc.StartInfo.FileName = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe";
proc.StartInfo.Arguments = "http:\\www.anyurl.com";
proc.Start();
But now, how do I make Chrome open a page with a specific request having Basic Authentication in the request header? I found the code below, but I don't know how to merge the two snippets.
var webRequest = (HttpWebRequest)WebRequest.Create("http://localhost:51232/");
webRequest.Method = "GET";
webRequest.ContentType = "application/json";
webRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36";
webRequest.ContentLength = 0; // added per comment
string autorization = "username" + ":" + "Password";
byte[] binaryAuthorization = System.Text.Encoding.UTF8.GetBytes(autorization);
autorization = Convert.ToBase64String(binaryAuthorization);
autorization = "Basic " + autorization;
webRequest.Headers.Add("AUTHORIZATION", autorization);
var webResponse = (HttpWebResponse)webRequest.GetResponse();
if (webResponse.StatusCode != HttpStatusCode.OK) Console.WriteLine("{0}", webResponse.Headers);
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
{
string s = reader.ReadToEnd();
Console.WriteLine(s);
reader.Close();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
