Skip to content

Instantly share code, notes, and snippets.

@shatulsky
Created March 16, 2018 20:35
Show Gist options
  • Save shatulsky/5c802d5506837ef13a3a042b00509b31 to your computer and use it in GitHub Desktop.
Save shatulsky/5c802d5506837ef13a3a042b00509b31 to your computer and use it in GitHub Desktop.
public static string GetResponseWithCookies(string url, Dictionary<string, string> cookieNameValues) {
using (var webClient = new WebClient()) {
var uri = new Uri(url);
var webRequest = WebRequest.Create(uri);
foreach (var nameValue in cookieNameValues) {
webRequest.TryAddCookie(new Cookie(nameValue.Key, nameValue.Value, "/", uri.Host));
}
var response = webRequest.GetResponse();
var receiveStream = response.GetResponseStream();
var readStream = new StreamReader(receiveStream, Encoding.UTF8);
var htmlCode = readStream.ReadToEnd();
return htmlCode;
}
}
static public bool TryAddCookie(this WebRequest webRequest, Cookie cookie) {
HttpWebRequest httpRequest = webRequest as HttpWebRequest;
if (httpRequest == null) {
return false;
}
if (httpRequest.CookieContainer == null) {
httpRequest.CookieContainer = new CookieContainer();
}
httpRequest.CookieContainer.Add(cookie);
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment