Well really I guess it would be https://login.live.com/, But regardless my goal is to make a windows application that will be able to log into bing.com. Right now I have a button on my windows form that's purpose is to log into bing.com. I found some code on how to log into websites and tried to implement it but to no avail. Right now this is what I have in the button click event:
var loginAddress = "https://login.live.com/";
var loginData = new NameValueCollection
{
{ "username", "myUserName" },
{ "password", "myPassword" }
};
var client = new CookieAwareWebClient();
client.Login(loginAddress, loginData);
Process.Start("IExplore.exe", "https://login.live.com/");
Here is my CookieAwareWebClient class code:
public class CookieAwareWebClient : WebClient
{
public void Login(string loginPageAddress, NameValueCollection loginData)
{
CookieContainer container;
var request = (HttpWebRequest)WebRequest.Create(loginPageAddress);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
var buffer = Encoding.ASCII.GetBytes(loginData.ToString());
request.ContentLength = buffer.Length;
var requestStream = request.GetRequestStream();
requestStream.Write(buffer, 0, buffer.Length);
requestStream.Close();
container = request.CookieContainer = new CookieContainer();
var response = request.GetResponse();
response.Close();
CookieContainer = container;
}
public CookieAwareWebClient(CookieContainer container)
{
CookieContainer = container;
}
public CookieAwareWebClient()
: this(new CookieContainer())
{ }
public CookieContainer CookieContainer { get; private set; }
protected override WebRequest GetWebRequest(Uri address)
{
var request = (HttpWebRequest)base.GetWebRequest(address);
request.CookieContainer = CookieContainer;
return request;
}
}
Related
I am trying to move change some methods from httpwebrequest to httpclient. I have done most of the work but stuck with this one. Can someone help to achieve this.
string url = someurl;
HttpWebRequest request = CreateRequest(url);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.ServicePoint.Expect100Continue = false;
string body = #"somestring here.";
byte[] postBytes = Encoding.UTF8.GetBytes(body);
request.ContentLength = postBytes.Length;
Stream stream = request.GetRequestStream();
stream.Write(postBytes, 0, postBytes.Length);
stream.Close();
response = (HttpWebResponse)request.GetResponse();
I need to convert this method using HttpClient.
This is what I have tried.
string url = someurl;
var client = new HttpClient();;
client.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));//ACCEPT header
//request.ContentType = "application/x-www-form-urlencoded";
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post,url);
string body = #"somestring here...";
var content = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded");
request.Content = content;
var ss = client.PostAsync(url,content).Result;
string str2 = await ss.Content.ReadAsStringAsync();
and I am not getting this part to work.
string body = #"somestring here.";
byte[] postBytes = Encoding.UTF8.GetBytes(body);
request.ContentLength = postBytes.Length;
Stream stream = request.GetRequestStream();
stream.Write(postBytes, 0, postBytes.Length);
stream.Close();
This is the sample client class which I use most of the time. You can use either PostAsync or SendAsync
public class RestClient
{
public bool IsDisposed { get; private set; }
public HttpClient BaseClient { get; private set; }
private readonly string jsonMediaType = "application/json";
public RestClient(string hostName, string token, HttpClient client)
{
BaseClient = client;
BaseClient.BaseAddress = new Uri(hostName);
BaseClient.DefaultRequestHeaders.Add("Authorization", token);
}
public async Task<string> PostAsync(string resource, string postData)
{
StringContent strContent = new StringContent(postData, Encoding.UTF8, jsonMediaType);
HttpResponseMessage responseMessage = await BaseClient.PostAsync(resource, strContent).ConfigureAwait(false);
responseMessage.RaiseExceptionIfFailed();
return await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);
}
public async Task<string> SendAsync(HttpMethod method, string resource, string token, string postData)
{
var resourceUri = new Uri(resource, UriKind.Relative);
var uri = new Uri(BaseClient.BaseAddress, resourceUri);
HttpRequestMessage request = new HttpRequestMessage(method, uri);
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
if (!string.IsNullOrEmpty(postData))
{
request.Content = new StringContent(postData, Encoding.UTF8, jsonMediaType);
}
HttpResponseMessage response = BaseClient.SendAsync(request).Result;
response.RaiseExceptionIfFailed();
return await response.Content.ReadAsStringAsync();
}
protected virtual void Dispose(bool isDisposing)
{
if (IsDisposed)
{
return;
}
if (isDisposing)
{
BaseClient.Dispose();
}
IsDisposed = true;
}
public virtual void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~RestClient()
{
Dispose(false);
}
}
I login with HTTPWebRequest and transfer the CookieContainer to the new class and want my WebClient to log in with this cookie and download a site as string. But I only get the source code of the login page, so it seems like the webclient won't login.
This is my current code:
BasicAuthentication login = new BasicAuthentication();
CookieContainer cookieJar = login.getCookie();
WebClientEx client = new WebClientEx();
client.Cookies = cookieJar;
And the WebClientEx Class
class WebClientEx : WebClient
{
private CookieContainer _cookies;
private string _ref;
public WebClientEx()
{
_cookies = new CookieContainer();
}
public CookieContainer Cookies
{
get { return _cookies; }
set { _cookies = value; }
}
protected override WebRequest GetWebRequest(System.Uri address)
{
var webReq = base.GetWebRequest(address);
if (webReq is HttpWebRequest)
{
var req = (HttpWebRequest)webReq;
req.CookieContainer = _cookies;
if (_ref != null)
{
req.Referer = _ref;
}
}
_ref = address.ToString();
return webReq;
}
protected override void Dispose(bool disposing)
{
_cookies = null;
base.Dispose(disposing);
}
}
I just get an Answer to my question.
Here's a example of my code:
WebClient client = new WebClient();
client.Headers.Add(HttpRequestHeader.Cookie, "cookievalue");
string download = client.DownloadString("url");
output.Text = download;
In the variable cookievalue I only enter the cookiename=cookievalue.
I get the name and the value from Postman, a useful google chrome tool.
I just have to make sure that i can redirect to any login proteccted page with postman and when this is true, then I can use cookiename and cookievalue to login my webclient and see all pages and download sites with downloadString.
I have the following code:
What do I put as the second argument for GetPage?
The second argument should be the previous cookie request of the same url.
for example I put google.com as the first argument to get the cookie when I make a get Request, but for the second how do I insert it?
static void Main()
{
GetPage("http://google.com/",cookieContainer??);
}
public class CookieAwareWebClient : WebClient
{
public CookieAwareWebClient(CookieContainer container)
{
CookieContainer = container;
}
public CookieAwareWebClient()
: this(new CookieContainer())
{ }
public CookieContainer CookieContainer { get; private set; }
protected override WebRequest GetWebRequest(Uri address)
{
var request = (HttpWebRequest)base.GetWebRequest(address);
request.CookieContainer = CookieContainer;
return request;
}
}
public HtmlAgilityPack.HtmlDocument GetPage(string url, CookieContainer CookieContainer)
{
Uri absoluteUri = new Uri("http://google.com/");
var cookies = CookieContainer.GetCookies(absoluteUri);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = new CookieContainer();
foreach (Cookie cookie in cookies)
{
request.CookieContainer.Add(cookie);
}
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
var stream = response.GetResponseStream();
using (var reader = new StreamReader(stream))
{
string html = reader.ReadToEnd();
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
return doc;
}
}
On the local network i have a similar page to this : http://demo.phpmyadmin.net/master (here use: username = "root", pass = blank)
In a Winforms app i need to pass the login/password and get this HTML: http://demo.phpmyadmin.net/master/server_status.php?db=&token=fda5205792a3caf29517c97c59ab1599
I'm looking for 3 days for a solution, but i can not get pass the login part.
This it the best i've got.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var client = new CookieAwareWebClient();
client.BaseAddress = #"http://demo.phpmyadmin.net/master";
var loginData = new NameValueCollection();
loginData.Add("input_username", "root");
//loginData.Add("password", "YourPassword");
client.UploadValues(#"http://demo.phpmyadmin.net/master", "POST", loginData);
string htmlSource = client.DownloadString("http://demo.phpmyadmin.net/master/server_status.php?db=&token=fda5205792a3caf29517c97c59ab1599");
richTextBox1.Text = htmlSource;
}
}
public class CookieAwareWebClient : WebClient
{
private CookieContainer cookie = new CookieContainer();
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = cookie;
}
return request;
}
}
This question already has answers here:
Using CookieContainer with WebClient class
(5 answers)
Accept Cookies in WebClient?
(3 answers)
Closed 8 years ago.
I logged site by httprequest and cookie in varible cookiecontanse . But now i need to set cookie got for webclient . I used line
webClient.Headers.Add(HttpRequestHeader.Cookie,cookiecontanse.ToString)
But not work. Why ?
Usage :
CookieContainer cookieJar = new CookieContainer();
cookieJar.Add(new Cookie("my_cookie", "cookie_value", "/", "mysite"));
CookieAwareWebClient client = new CookieAwareWebClient(cookieJar);
string response = client.DownloadString("http://example.com/response_with_cookie_only.php");
public class CookieAwareWebClient : WebClient
{
public CookieContainer CookieContainer { get; set; }
public Uri Uri { get; set; }
public CookieAwareWebClient()
: this(new CookieContainer())
{
}
public CookieAwareWebClient(CookieContainer cookies)
{
this.CookieContainer = cookies;
}
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = this.CookieContainer;
}
HttpWebRequest httpRequest = (HttpWebRequest)request;
httpRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
return httpRequest;
}
protected override WebResponse GetWebResponse(WebRequest request)
{
WebResponse response = base.GetWebResponse(request);
String setCookieHeader = response.Headers[HttpResponseHeader.SetCookie];
if (setCookieHeader != null)
{
//do something if needed to parse out the cookie.
if (setCookieHeader != null)
{
Cookie cookie = new Cookie(); //create cookie
this.CookieContainer.Add(cookie);
}
}
return response;
}
}
You will see two overridden methods for GetWebRequest and GetWebResponse. These methods can be overridden to handle the cookie container.