The API was built to use BrowserMob proxy with Selenium.
public class Proxy
{
private const string Host = "localhost";
private readonly int port;
private readonly string path = string.Empty;
private Process serverProcess;
public Proxy(string path) : this(path, 81)
{
}
public Proxy(string path, int port)
{
this.path = path;
this.port = port;
}
public string Url
{
get { return string.Format("http://{0}:{1}", Host, this.port.ToString(CultureInfo.InvariantCulture)); }
}
// Start the server and connect to proxy
public void Start()
{
this.serverProcess = new Process
{
StartInfo = { FileName = this.path }
};
if (this.port != 0)
{
this.serverProcess.StartInfo.Arguments = string.Format("--port={0}", this.port);
}
try
{
this.serverProcess.Start();
int count = 0;
while (!this.IsListening())
{
Thread.Sleep(1000);
count++;
if (count == 30)
{
throw new Exception("Can not connect to specified Proxy");
}
}
}
catch
{
this.serverProcess.Dispose();
this.serverProcess = null;
throw;
}
}
// Stop the currently running proxy
public void Stop()
{
if (this.serverProcess != null && !this.serverProcess.HasExited)
{
this.serverProcess.CloseMainWindow();
this.serverProcess.Dispose();
this.serverProcess.Close();
}
}
public Client CreateProxy()
{
return new Client(this.Url);
}
private static WebResponse MakeRequest(string url, string method, string reference = null)
{
Console.WriteLine(url);
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method;
if (reference != null)
{
byte[] requestBytes = Encoding.UTF8.GetBytes(reference);
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(requestBytes, 0, requestBytes.Length);
requestStream.Close();
}
request.ContentType = "application/x-www-form-urlencoded";
}
else
{
request.ContentLength = 0;
}
return request.GetResponse();
}
private bool IsListening()
{
try
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(Host, this.port);
socket.Close();
return true;
}
catch (Exception)
{
return false;
}
}
}
public class Client
{
private static string proxy;
private readonly string url;
private readonly short port;
private readonly string baseUrlProxy;
public Client(string url)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentException("url not supplied", "url");
}
this.url = url;
this.baseUrlProxy = string.Format("{0}/proxy", this.url);
using (var response = MakeRequest(this.baseUrlProxy, "POST"))
{
var responseStream = response.GetResponseStream();
if (responseStream == null)
{
throw new Exception("No response from proxy");
}
using (var responseStreamReader = new StreamReader(responseStream))
{
var jsonReader = new JsonTextReader(responseStreamReader);
var token = JToken.ReadFrom(jsonReader);
var portToken = token.SelectToken("port");
if (portToken == null)
{
throw new Exception("No port number returned from proxy");
}
this.port = (short)portToken;
}
}
var parts = url.Split(':');
proxy = parts[1].TrimStart('/') + ":" + this.port;
}
public string SeleniumProxy
{
get { return proxy; }
}
public Har GetHar()
{
using (var response = MakeRequest(string.Format("{0}/{1}/har", this.baseUrlProxy, this.port), "GET"))
{
using (var responseStream = response.GetResponseStream())
{
if (responseStream == null)
{
return null;
}
using (var responseStreamReader = new StreamReader(responseStream))
{
var json = responseStreamReader.ReadToEnd();
return JsonConvert.DeserializeObject<Har>(json);
}
}
}
}
public string GetHarString()
{
using (var response = MakeRequest(string.Format("{0}/{1}/har", this.baseUrlProxy, this.port), "GET"))
{
using (var responseStream = response.GetResponseStream())
{
if (responseStream == null)
{
return null;
}
using (var responseStreamReader = new StreamReader(responseStream))
{
var json = responseStreamReader.ReadToEnd();
return json;
}
}
}
}
public void NewHar(string reference = null)
{
MakeRequest(string.Format("{0}/{1}/har", this.baseUrlProxy, this.port), "PUT", reference);
}
public void NewPage(string reference)
{
MakeRequest(string.Format("{0}/{1}/har/pageRef", this.baseUrlProxy, this.port), "PUT", reference);
}
public void RemapHost(string host, string ipaddress)
{
MakeJsonRequest(string.Format("{0}/{1}/hosts", this.baseUrlProxy, this.port), "POST", "{\"" + host + "\":\"" + ipaddress + "\"}");
}
/// <summary>
/// shuts down the proxy and closes the port
/// </summary>
public void Close()
{
MakeRequest(string.Format("{0}/{1}", this.baseUrlProxy, this.port), "DELETE");
}
private static WebResponse MakeRequest(string url, string method, string reference = null)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method;
if (reference != null)
{
byte[] requestBytes = Encoding.UTF8.GetBytes(reference);
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(requestBytes, 0, requestBytes.Length);
requestStream.Close();
}
request.ContentType = "application/x-www-form-urlencoded";
}
else
{
request.ContentLength = 0;
}
return request.GetResponse();
}
private static WebResponse MakeJsonRequest(string url, string method, string payload)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method;
if (payload != null)
{
request.ContentType = "text/json";
request.ContentLength = payload.Length;
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(payload);
streamWriter.Flush();
streamWriter.Close();
}
}
else
{
request.ContentLength = 0;
}
return request.GetResponse();
}
}
Elsewhere in my code I'm simply getting the har data from the client for my Selenium test (after the test has ended) and saving this in a .har file.