/**
*
* @param internalPort Port of the local proxy (listening on localhost).
* @param proxyHost The (external) proxy to use.
* @param credentials The credentials needed for the external proxy.
* @return The created proxy server.
* @throws Exception
*/
private ProxyServer createAndConfigureProxyServer(int internalPort,
HttpHost proxyHost, UsernamePasswordCredentials credentials)
throws Exception{
// Set up the internal proxy server and start it, because otherwise the
// http client is not started and we end up with a NP.
ProxyServer server = new ProxyServer(internalPort);
server.start();
DefaultHttpClient httpClient = extract();
AuthScope authScope = new AuthScope(proxyHost.getHostName(),
proxyHost.getPort());
httpClient.getCredentialsProvider().setCredentials(authScope,
credentials);
HttpHost proxy = new HttpHost(proxyHost.getHostName(),
proxyHost.getPort());
httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
proxy);
return server;
}
private DefaultHttpClient extract() throws NoSuchFieldException,
IllegalAccessException {
// The httpclient has to be manipulated in order to be configured
// to use the proxy is private, so we have to rely on reflection.
Field clientField = ProxyServer.class.getDeclaredField("client");
setFieldAccessible(clientField);
BrowserMobHttpClient client = (BrowserMobHttpClient) clientField
.get(server);
Field httpClientfield = BrowserMobHttpClient.class
.getDeclaredField("httpClient");
setFieldAccessible(httpClientfield);
DefaultHttpClient httpClient = (DefaultHttpClient) httpClientfield
.get(client);
return httpClient;
}
private void setFieldAccessible(Field clientField) {
if (!clientField.isAccessible()) {
clientField.setAccessible(true);
}
}