Advertisement
Guest User

Untitled

a guest
Jun 23rd, 2016
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. public static string GetRealm(string url)
  2. {
  3. var request = (HttpWebRequest)WebRequest.Create(url);
  4. try
  5. {
  6. using (request.GetResponse())
  7. {
  8. return null;
  9. }
  10. }
  11. catch (WebException e)
  12. {
  13. if (e.Response == null) return null;
  14. var auth = e.Response.Headers[HttpResponseHeader.WwwAuthenticate];
  15. if (auth == null) return null;
  16. // Example auth value:
  17. // Basic realm="Some realm"
  18. return ...Extract the value of "realm" here (with a regex perhaps)...
  19. }
  20. }
  21.  
  22. // Create a request to a URL
  23. WebRequest myReq = WebRequest.Create(url);
  24. string usernamePassword = "username:password";
  25. //Use the CredentialCache so we can attach the authentication to the request
  26. CredentialCache mycache = new CredentialCache();
  27. mycache.Add(new Uri(url), "Basic", new NetworkCredential("username", "password"));
  28. myReq.Credentials = mycache;
  29. myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
  30. //Send and receive the response
  31. WebResponse wr = myReq.GetResponse();
  32. Stream receiveStream = wr.GetResponseStream();
  33. StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
  34. string content = reader.ReadToEnd();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement