Example usage for org.apache.http.params HttpParams setParameter

List of usage examples for org.apache.http.params HttpParams setParameter

Introduction

In this page you can find the example usage for org.apache.http.params HttpParams setParameter.

Prototype

HttpParams setParameter(String str, Object obj);

Source Link

Usage

From source file:org.eweb4j.spiderman.plugin.util.PageFetcherImpl.java

/**
 * client?Header?Cookie//w w w.j  a  v a 2 s. c  o m
 * @param aconfig
 * @param cookies
 */
public void init(Site _site) {
    //HTTP?
    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.USER_AGENT, config.getUserAgentString());
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeout());
    params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout());

    HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params);
    paramsBean.setVersion(HttpVersion.HTTP_1_1);
    paramsBean.setContentCharset("UTF-8");
    paramsBean.setUseExpectContinue(false);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));

    if (config.isIncludeHttpsPages())
        schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

    connectionManager = new ThreadSafeClientConnManager(schemeRegistry);
    connectionManager.setMaxTotal(config.getMaxTotalConnections());
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost());
    httpClient = new DefaultHttpClient(connectionManager, params);

    httpClient.getParams().setIntParameter("http.socket.timeout", 60000);
    httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);
    httpClient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, config.isFollowRedirects());
    //      HttpClientParams.setCookiePolicy(httpClient.getParams(),CookiePolicy.BEST_MATCH);

    //?
    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            Header contentEncoding = entity.getContentEncoding();
            if (contentEncoding != null) {
                HeaderElement[] codecs = contentEncoding.getElements();
                for (HeaderElement codec : codecs) {
                    //?GZIP
                    if (codec.getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                    }
                }
            }
        }
    });

    if (_site != null) {
        this.site = _site;
        if (this.site.getHeaders() != null && this.site.getHeaders().getHeader() != null) {
            for (org.eweb4j.spiderman.xml.Header header : this.site.getHeaders().getHeader()) {
                this.addHeader(header.getName(), header.getValue());
            }
        }
        if (this.site.getCookies() != null && this.site.getCookies().getCookie() != null) {
            for (org.eweb4j.spiderman.xml.Cookie cookie : this.site.getCookies().getCookie()) {
                this.addCookie(cookie.getName(), cookie.getValue(), cookie.getHost(), cookie.getPath());
            }
        }
    }
}

From source file:processing.core.PRequest.java

/** @hidden */
public void run() {
    try {/*from w w  w. jav  a 2  s .  co  m*/
        if (client == null) {
            //instance the client
            client = new DefaultHttpClient();
            HttpParams params = client.getParams();
            //open connection to server
            //request type depends on content type var
            if (contentType != null) {
                request = new HttpPost(url);
                //which content types are posted?               
                params.setParameter("Content-Type", contentType);
                //create a byte array entity and add to post
                if (bytes != null) {
                    ByteArrayEntity entity = new ByteArrayEntity(bytes);
                    ((HttpPost) request).setEntity(entity);
                    //we can release the request bytes and reuse the
                    // reference
                    bytes = null;
                }
            } else {
                request = new HttpGet(url);
            }
            if (authorization != null) {
                params.setParameter("Authorization", authorization);
            }
            params.setParameter("Connection", "close");
            request.setParams(params);
            //
            client.execute(request, new StateResponseHandler<Integer>());
            // done, notify midlet
            boolean notify = false;
            synchronized (this) {
                if (state == STATE_OPENED) {
                    state = STATE_CONNECTED;
                    notify = true;
                }
            }
            if (notify) {
                midlet.enqueueLibraryEvent(this, EVENT_CONNECTED, null);
            }
        } else {
            synchronized (this) {
                if (state == STATE_CONNECTED) {
                    state = STATE_FETCHING;
                } else {
                    throw new Exception("Not connected.");
                }
            }
            // read the response
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int bytesRead = is.read(buffer);
            while (bytesRead >= 0) {
                baos.write(buffer, 0, bytesRead);
                bytesRead = is.read(buffer);
            }
            buffer = null;
            buffer = baos.toByteArray();
            // done, notify midlet
            boolean notify = false;
            synchronized (this) {
                if (state == STATE_FETCHING) {
                    state = STATE_DONE;
                    notify = true;
                }
            }
            if (notify) {
                midlet.enqueueLibraryEvent(this, EVENT_DONE, buffer);
            }
        }
    } catch (Exception e) {
        boolean notify = false;
        synchronized (this) {
            if ((state == STATE_CONNECTED) || (state == STATE_FETCHING)) {
                notify = true;
            }
        }
        close();
        if (notify) {
            synchronized (this) {
                state = STATE_ERROR;
            }
            midlet.enqueueLibraryEvent(this, EVENT_ERROR, e.getMessage());
        }
    } finally {

    }
}

From source file:de.derschimi.proxyservlet.TestServlet.java

@Override
public void init() throws ServletException {
    String doLogStr = getConfigParam(P_LOG);
    if (doLogStr != null) {
        this.doLog = Boolean.parseBoolean(doLogStr);
    }/*from ww  w  . j  ava  2  s .  com*/

    String doForwardIPString = getConfigParam(P_FORWARDEDFOR);
    if (doForwardIPString != null) {
        this.doForwardIP = Boolean.parseBoolean(doForwardIPString);
    }
    path = getConfigParam("path");

    initTarget();//sets target*

    HttpParams hcParams = new BasicHttpParams();
    hcParams.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES);
    readConfigParam(hcParams, ClientPNames.HANDLE_REDIRECTS, Boolean.class);
    proxyClient = createHttpClient(hcParams);
}

From source file:org.bungeni.ext.integration.bungeniportal.BungeniAppConnector.java

private OAuthToken oauthAuthorize(String oauthAuthorizeURL) throws IOException, JDOMException {
    // get pag einfo 
    OAuthToken token = null;/*from  w  w  w. j a  v  a  2 s .co m*/
    WebResponse wr = this.getUrl(oauthAuthorizeURL, false);
    if (wr.statusCode == 200) {
        HashMap<String, ContentBody> formfields = BungeniServiceAccess.getInstance()
                .getAuthorizeFormFieldValues(wr.responseBody);
        if (!formfields.isEmpty()) {
            HttpContext context = new BasicHttpContext();
            // we use the form authorize URL here 
            final HttpPost post = new HttpPost(this.oauthAuthFormUrl);
            // we disable the automatic redirect of the URL since we want to grab 
            // the refresh token and anyway the redirect is to a dummy url
            final HttpParams params = new BasicHttpParams();
            params.setParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.FALSE);
            post.setParams(params);
            post.setEntity(getMultiPartEntity(formfields));
            HttpResponse authResponse = getClient().execute(post, context);
            String redirectLocation = "";
            Header locationHeader = authResponse.getFirstHeader("location");
            //consume response
            //ResponseHandler<String> responseHandler = new BasicResponseHandler();
            //responseHandler.handleResponse(authResponse);

            if (locationHeader != null) {
                redirectLocation = locationHeader.getValue();
                EntityUtils.consumeQuietly(authResponse.getEntity());
                try {
                    token = getAuthToken(redirectLocation);
                    // do someting with the returned codes
                } catch (MalformedURLException ex) {
                    log.error("Error while getting oauthtoken", ex);
                } catch (URISyntaxException ex) {
                    log.error("Error while getting oauthtoken", ex);
                }

            } else {
                EntityUtils.consumeQuietly(authResponse.getEntity());
                throw new IOException(authResponse.getStatusLine().toString());
            }
        } else {
            throw new IOException("Authorization failed !");
        }
    }
    return token;
}

From source file:com.stepsdk.android.api.APIClient.java

public HttpEntity httpGet(String url, Map<String, String> headerParams)
        throws NetworkDownException, HttpGetException {
    HttpEntity entity = null;// w  ww  .ja  va 2  s . c  o m

    mHttpclient = new DefaultHttpClient();

    ClientConnectionManager mgr = mHttpclient.getConnectionManager();
    HttpParams params = mHttpclient.getParams();
    if (WEB_USER_AGENT != null)
        params.setParameter(CoreProtocolPNames.USER_AGENT, WEB_USER_AGENT);
    int timeoutConnection = 3000;
    HttpConnectionParams.setConnectionTimeout(params, timeoutConnection);
    int timeoutSocket = 5000;
    HttpConnectionParams.setSoTimeout(params, timeoutSocket);
    mHttpclient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()),
            params);

    // Allow redirection from server
    // ref: http://stackoverflow.com/questions/3658721/httpclient-4-error-302-how-to-redirect
    mHttpclient.setRedirectHandler(new DefaultRedirectHandler() {
        @Override
        public boolean isRedirectRequested(HttpResponse response, HttpContext context) {
            boolean isRedirect = super.isRedirectRequested(response, context);
            if (!isRedirect) {
                int responseCode = response.getStatusLine().getStatusCode();
                if (responseCode == 302) {
                    return true;
                }
            }
            return isRedirect;
        }
    });

    HttpGet get = new HttpGet(url);

    if (headerParams == null) {
        headerParams = new HashMap<String, String>();
    }

    Iterator<String> i = headerParams.keySet().iterator();

    while (i.hasNext()) {
        String key = i.next();
        get.addHeader(key, headerParams.get(key));
    }

    Integer retryRemaining = 3;

    while (entity == null) {
        try {

            if (!DeviceUtil.checkPermission(mContext, "android.permission.ACCESS_NETWORK_STATE"))
                throw new NetworkDownException(
                        "ACCESS_NETWORK_STATE permission not set in AndroidManifest.xml");

            if (!DeviceUtil.checkPermission(mContext, "android.permission.INTERNET"))
                throw new NetworkDownException("INTERNET permission not set in AndroidManifest.xml");

            if (!NetworkUtil.isOnline(mContext))
                throw new NetworkDownException();

            HttpResponse response = mHttpclient.execute(get);
            if (response.getStatusLine().getStatusCode() == 404)
                throw new HttpGetException("404");
            entity = response.getEntity();
        } catch (ClientProtocolException e) {
            if (retryRemaining-- != 0) {
                entity = null;
            } else {
                throw new HttpGetException(e.getMessage());
            }
        } catch (IOException e) {
            if (retryRemaining-- != 0) {
                entity = null;
            } else {
                throw new HttpGetException(e.getMessage());
            }
        }
    }

    return entity;
}

From source file:de.betterform.connector.http.AbstractHTTPConnector.java

protected void execute(HttpRequestBase httpRequestBase) throws Exception {
    //      (new HttpClient()).executeMethod(httpMethod);
    //HttpClient client = new HttpClient();
    HttpParams httpParams = new BasicHttpParams();

    DefaultHttpClient client = ConnectorFactory.getFactory().getHttpClient(httpParams);

    if (!getContext().containsKey(AbstractHTTPConnector.SSL_CUSTOM_SCHEME)) {
        LOGGER.debug("SSL_CUSTOM_SCHEME");
        LOGGER.debug("SSL_CUSTOM_SCHEME: Factory: "
                + Config.getInstance().getProperty(AbstractHTTPConnector.HTTPCLIENT_SSL_CONTEXT));
        String contextPath = Config.getInstance().getProperty(AbstractHTTPConnector.HTTPCLIENT_SSL_CONTEXT);
        if (contextPath != null) {
            initSSLScheme(contextPath);//from   ww w.j a va 2  s .c o  m
        }
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("context params>>>");
        Map map = getContext();
        Iterator keys = map.keySet().iterator();
        while (keys.hasNext()) {
            String key = keys.next().toString();
            Object value = map.get(key);
            if (value != null)
                LOGGER.debug(key + "=" + value.toString());
        }
        LOGGER.debug("<<<end params");
    }
    String username = null;
    String password = null;
    String realm = null;

    //add custom header to signal XFormsFilter to not process this internal request
    //httpMethod.setRequestHeader(BetterFORMConstants.BETTERFORM_INTERNAL,"true");
    httpRequestBase.addHeader(BetterFORMConstants.BETTERFORM_INTERNAL, "true");

    /// *** copy all keys in map HTTP_REQUEST_HEADERS as http-submissionHeaders
    if (getContext().containsKey(HTTP_REQUEST_HEADERS)) {
        RequestHeaders httpRequestHeaders = (RequestHeaders) getContext().get(HTTP_REQUEST_HEADERS);

        // Iterator it =
        Map headersToAdd = new HashMap();
        for (RequestHeader header : httpRequestHeaders.getAllHeaders()) {
            String headername = header.getName();
            String headervalue = header.getValue();

            if (headername.equals("username")) {
                username = headervalue;
            } else if (headername.equals("password")) {
                password = headervalue;
            } else if (headername.equals("realm")) {
                realm = headervalue;
            } else {
                if (headersToAdd.containsKey(headername)) {
                    String formerValue = (String) headersToAdd.get(headername);
                    headersToAdd.put(headername, formerValue + "," + headervalue);
                } else {
                    if (headername.equals("accept-encoding")) {
                        // do nothing
                        LOGGER.debug("do not add accept-encoding:" + headervalue + " for request");
                    } else {
                        headersToAdd.put(headername, headervalue);
                        if (LOGGER.isDebugEnabled()) {
                            LOGGER.debug("setting header: " + headername + " value: " + headervalue);
                        }
                    }
                }
            }
        }
        Iterator keyIterator = headersToAdd.keySet().iterator();
        while (keyIterator.hasNext()) {
            String key = (String) keyIterator.next();
            //httpMethod.setRequestHeader(new Header(key,(String) headersToAdd.get(key)));
            httpRequestBase.setHeader(key, (String) headersToAdd.get(key));
            //httpRequestBase.addHeader(key, (String) headersToAdd.get(key));
        }
    }
    if (httpRequestBase.containsHeader("Content-Length")) {
        //remove content-length if present httpclient will recalucalte the value.
        httpRequestBase.removeHeaders("Content-Length");
    }
    if (username != null && password != null) {
        URI targetURI = null;
        //targetURI = httpMethod.getURI();
        targetURI = httpRequestBase.getURI();
        //client.getParams().setAuthenticationPreemptive(true);

        Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
        if (realm == null) {
            realm = AuthScope.ANY_REALM;
        }
        //client.getState().setCredentials(new AuthScope(targetURI.getHost(), targetURI.getPort(), realm), defaultcreds);
        client.getCredentialsProvider()
                .setCredentials(new AuthScope(targetURI.getHost(), targetURI.getPort(), realm), defaultcreds);
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();

        authCache.put(new HttpHost(targetURI.getHost()), basicAuth);
        BasicHttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);

        //Needed? httpMethod.setDoAuthentication(true);

    }
    //alternative method for non-tomcat servers
    if (getContext().containsKey(REQUEST_COOKIE)) {
        //HttpState state = client.getState();
        HttpParams state = client.getParams();

        //state.setCookiePolicy(CookiePolicy.COMPATIBILITY);
        state.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

        if (getContext().get(REQUEST_COOKIE) instanceof Cookie[]) {
            Cookie[] cookiesIn = (Cookie[]) getContext().get(REQUEST_COOKIE);
            if (cookiesIn[0] != null) {
                for (int i = 0; i < cookiesIn.length; i++) {
                    Cookie cookie = cookiesIn[i];
                    //state.addCookie(cookie);
                    client.getCookieStore().addCookie(cookie);
                }
                /*
                  Cookie[] cookies = state.getCookies();
                        
                Header cookieOut = new CookieSpecBase().formatCookieHeader(cookies);
                httpMethod.setRequestHeader(cookieOut);
                client.setState(state);
                  */
                List<Cookie> cookies = client.getCookieStore().getCookies();
                List<Header> cookieHeaders = new BrowserCompatSpec().formatCookies(cookies);
                Header[] headers = cookieHeaders.toArray(new Header[0]);

                for (int i = 0; i < headers.length; i++) {
                    httpRequestBase.addHeader(headers[i]);
                }

                client.setParams(state);
            }
        } else {
            throw new MalformedCookieException(
                    "Cookies must be passed as org.apache.commons.httpclient.Cookie objects.");
        }
    }

    if (getContext().containsKey(AbstractHTTPConnector.SSL_CUSTOM_SCHEME)) {
        LOGGER.debug("Using customSSL-Protocol-Handler");
        Iterator<Scheme> schemes = ((Vector<Scheme>) getContext().get(AbstractHTTPConnector.SSL_CUSTOM_SCHEME))
                .iterator();

        while (schemes.hasNext()) {
            client.getConnectionManager().getSchemeRegistry().register(schemes.next());
        }
    }

    if (httpRequestBase.getURI().isAbsolute()) {
        httpRequestBase.setHeader("host", httpRequestBase.getURI().getHost());
    }

    HttpResponse httpResponse = client.execute(httpRequestBase);
    statusCode = httpResponse.getStatusLine().getStatusCode();
    reasonPhrase = httpResponse.getStatusLine().getReasonPhrase();
    try {
        if (statusCode >= 300) {
            // Allow 302 only
            if (statusCode != 302) {
                throw new XFormsInternalSubmitException(statusCode, reasonPhrase,
                        EntityUtils.toString(httpResponse.getEntity()), XFormsConstants.RESOURCE_ERROR);
            }
        }
        this.handleHttpMethod(httpResponse);
    } catch (Exception e) {

        LOGGER.trace("AbstractHTTPConnector Exception: ", e);
        try {
            throw new XFormsInternalSubmitException(httpResponse.getStatusLine().getStatusCode(),
                    httpResponse.getStatusLine().getReasonPhrase(),
                    EntityUtils.toString(httpResponse.getEntity()), XFormsConstants.RESOURCE_ERROR);
        } catch (IOException e1) {
            throw new XFormsInternalSubmitException(httpResponse.getStatusLine().getStatusCode(),
                    httpResponse.getStatusLine().getReasonPhrase(), XFormsConstants.RESOURCE_ERROR);
        }
    }

}

From source file:io.hops.hopsworks.api.kibana.ProxyServlet.java

@Override
public void init() throws ServletException {
    String doLogStr = getConfigParam(P_LOG);
    if (doLogStr != null) {
        this.doLog = Boolean.parseBoolean(doLogStr);
    }/*from w  w  w.  j  a va2s .  c  o  m*/

    String doForwardIPString = getConfigParam(P_FORWARDEDFOR);
    if (doForwardIPString != null) {
        this.doForwardIP = Boolean.parseBoolean(doForwardIPString);
    }

    initTarget();//sets target*

    HttpParams hcParams = new BasicHttpParams();
    hcParams.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES);
    readConfigParam(hcParams, ClientPNames.HANDLE_REDIRECTS, Boolean.class);
    proxyClient = createHttpClient(hcParams);
}

From source file:net.vexelon.mobileops.GLBClient.java

/**
 * Initialize Http Client//from w  ww. j  av  a2  s . c o m
 */
private void initHttpClient() {

    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    params.setParameter(CoreProtocolPNames.USER_AGENT, UserAgentHelper.getRandomUserAgent());
    //params.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, HTTP.UTF_8);
    // Bugfix #1: The target server failed to respond
    params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);

    DefaultHttpClient client = new DefaultHttpClient(params);

    httpCookieStore = new BasicCookieStore();
    client.setCookieStore(httpCookieStore);

    httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, httpCookieStore);

    // Bugfix #1: Adding retry handler to repeat failed requests
    HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() {

        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {

            if (executionCount >= MAX_REQUEST_RETRIES) {
                return false;
            }

            if (exception instanceof NoHttpResponseException || exception instanceof ClientProtocolException) {
                return true;
            }

            return false;
        }
    };
    client.setHttpRequestRetryHandler(retryHandler);

    // SSL
    HostnameVerifier verifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    try {
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", new PlainSocketFactory(), 80));
        registry.register(new Scheme("https", new TrustAllSocketFactory(), 443));

        SingleClientConnManager connMgr = new SingleClientConnManager(client.getParams(), registry);

        httpClient = new DefaultHttpClient(connMgr, client.getParams());
    } catch (InvalidAlgorithmParameterException e) {
        //         Log.e(Defs.LOG_TAG, "", e);

        // init without connection manager
        httpClient = new DefaultHttpClient(client.getParams());
    }

    HttpsURLConnection.setDefaultHostnameVerifier(verifier);

}

From source file:com.jobaline.uiautomation.framework.selenium.phantomJsThreeHourTimeoutFix.HttpCommandExecutor.java

public HttpCommandExecutor(Map<String, CommandInfo> additionalCommands, URL addressOfRemoteServer) {
    try {//from   www .jav a 2  s. com
        remoteServer = addressOfRemoteServer == null
                ? new URL(System.getProperty("webdriver.remote.server", "http://localhost:4444/wd/hub"))
                : addressOfRemoteServer;
    } catch (MalformedURLException e) {
        throw new WebDriverException(e);
    }

    HttpParams params = new BasicHttpParams();
    // Use the JRE default for the socket linger timeout.
    params.setParameter(CoreConnectionPNames.SO_LINGER, -1);
    HttpClientParams.setRedirecting(params, false);

    synchronized (HttpCommandExecutor.class) {
        if (httpClientFactory == null) {
            httpClientFactory = new HttpClientFactory();
        }
    }
    client = httpClientFactory.getHttpClient();

    // PATCH start
    // HttpClientFactory has a hardcoded timeout of three hours.
    // This class is intended to be used only for phantomjs which runs locally so the timeouts will be set to a low value

    BasicHttpParams paramsPatched = (BasicHttpParams) client.getParams();
    paramsPatched.setIntParameter("http.connection.timeout", 90000); //  1 minute an a half
    paramsPatched.setIntParameter("http.socket.timeout", 90000); // 1 minute an a half
    ((DefaultHttpClient) client).setParams(params);

    // PATCH end

    if (addressOfRemoteServer != null && addressOfRemoteServer.getUserInfo() != null) {
        // Use HTTP Basic auth
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
                addressOfRemoteServer.getUserInfo());
        ((DefaultHttpClient) client).getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
    }

    // Some machines claim "localhost.localdomain" is the same as "localhost".
    // This assumption is not always true.

    String host = remoteServer.getHost().replace(".localdomain", "");

    targetHost = new HttpHost(host, remoteServer.getPort(), remoteServer.getProtocol());

    ImmutableMap.Builder<String, CommandInfo> builder = ImmutableMap.builder();
    for (Map.Entry<String, CommandInfo> entry : additionalCommands.entrySet()) {
        builder.put(entry.getKey(), entry.getValue());
    }

    builder.put(GET_ALL_SESSIONS, get("/sessions")).put(NEW_SESSION, post("/session"))
            .put(GET_CAPABILITIES, get("/session/:sessionId")).put(QUIT, delete("/session/:sessionId"))
            .put(GET_CURRENT_WINDOW_HANDLE, get("/session/:sessionId/window_handle"))
            .put(GET_WINDOW_HANDLES, get("/session/:sessionId/window_handles"))
            .put(GET, post("/session/:sessionId/url"))

            // The Alert API is still experimental and should not be used.
            .put(GET_ALERT, get("/session/:sessionId/alert"))
            .put(DISMISS_ALERT, post("/session/:sessionId/dismiss_alert"))
            .put(ACCEPT_ALERT, post("/session/:sessionId/accept_alert"))
            .put(GET_ALERT_TEXT, get("/session/:sessionId/alert_text"))
            .put(SET_ALERT_VALUE, post("/session/:sessionId/alert_text"))

            .put(GO_FORWARD, post("/session/:sessionId/forward")).put(GO_BACK, post("/session/:sessionId/back"))
            .put(REFRESH, post("/session/:sessionId/refresh"))
            .put(EXECUTE_SCRIPT, post("/session/:sessionId/execute"))
            .put(EXECUTE_ASYNC_SCRIPT, post("/session/:sessionId/execute_async"))
            .put(GET_CURRENT_URL, get("/session/:sessionId/url"))
            .put(GET_TITLE, get("/session/:sessionId/title"))
            .put(GET_PAGE_SOURCE, get("/session/:sessionId/source"))
            .put(SCREENSHOT, get("/session/:sessionId/screenshot"))
            .put(FIND_ELEMENT, post("/session/:sessionId/element"))
            .put(FIND_ELEMENTS, post("/session/:sessionId/elements"))
            .put(GET_ACTIVE_ELEMENT, post("/session/:sessionId/element/active"))
            .put(FIND_CHILD_ELEMENT, post("/session/:sessionId/element/:id/element"))
            .put(FIND_CHILD_ELEMENTS, post("/session/:sessionId/element/:id/elements"))
            .put(CLICK_ELEMENT, post("/session/:sessionId/element/:id/click"))
            .put(CLEAR_ELEMENT, post("/session/:sessionId/element/:id/clear"))
            .put(SUBMIT_ELEMENT, post("/session/:sessionId/element/:id/submit"))
            .put(GET_ELEMENT_TEXT, get("/session/:sessionId/element/:id/text"))
            .put(SEND_KEYS_TO_ELEMENT, post("/session/:sessionId/element/:id/value"))
            .put(UPLOAD_FILE, post("/session/:sessionId/file"))
            .put(GET_ELEMENT_VALUE, get("/session/:sessionId/element/:id/value"))
            .put(GET_ELEMENT_TAG_NAME, get("/session/:sessionId/element/:id/name"))
            .put(IS_ELEMENT_SELECTED, get("/session/:sessionId/element/:id/selected"))
            .put(IS_ELEMENT_ENABLED, get("/session/:sessionId/element/:id/enabled"))
            .put(IS_ELEMENT_DISPLAYED, get("/session/:sessionId/element/:id/displayed"))
            .put(HOVER_OVER_ELEMENT, post("/session/:sessionId/element/:id/hover"))
            .put(GET_ELEMENT_LOCATION, get("/session/:sessionId/element/:id/location"))
            .put(GET_ELEMENT_LOCATION_ONCE_SCROLLED_INTO_VIEW,
                    get("/session/:sessionId/element/:id/location_in_view"))
            .put(GET_ELEMENT_SIZE, get("/session/:sessionId/element/:id/size"))
            .put(GET_ELEMENT_ATTRIBUTE, get("/session/:sessionId/element/:id/attribute/:name"))
            .put(ELEMENT_EQUALS, get("/session/:sessionId/element/:id/equals/:other"))
            .put(GET_ALL_COOKIES, get("/session/:sessionId/cookie"))
            .put(ADD_COOKIE, post("/session/:sessionId/cookie"))
            .put(DELETE_ALL_COOKIES, delete("/session/:sessionId/cookie"))
            .put(DELETE_COOKIE, delete("/session/:sessionId/cookie/:name"))
            .put(SWITCH_TO_FRAME, post("/session/:sessionId/frame"))
            .put(SWITCH_TO_PARENT_FRAME, post("/session/:sessionId/frame/parent"))
            .put(SWITCH_TO_WINDOW, post("/session/:sessionId/window"))
            .put(GET_WINDOW_SIZE, get("/session/:sessionId/window/:windowHandle/size"))
            .put(GET_WINDOW_POSITION, get("/session/:sessionId/window/:windowHandle/position"))
            .put(SET_WINDOW_SIZE, post("/session/:sessionId/window/:windowHandle/size"))
            .put(SET_WINDOW_POSITION, post("/session/:sessionId/window/:windowHandle/position"))
            .put(MAXIMIZE_WINDOW, post("/session/:sessionId/window/:windowHandle/maximize"))
            .put(CLOSE, delete("/session/:sessionId/window"))
            .put(DRAG_ELEMENT, post("/session/:sessionId/element/:id/drag"))
            .put(GET_ELEMENT_VALUE_OF_CSS_PROPERTY, get("/session/:sessionId/element/:id/css/:propertyName"))
            .put(IMPLICITLY_WAIT, post("/session/:sessionId/timeouts/implicit_wait"))
            .put(SET_SCRIPT_TIMEOUT, post("/session/:sessionId/timeouts/async_script"))
            .put(SET_TIMEOUT, post("/session/:sessionId/timeouts"))
            .put(EXECUTE_SQL, post("/session/:sessionId/execute_sql"))
            .put(GET_LOCATION, get("/session/:sessionId/location"))
            .put(SET_LOCATION, post("/session/:sessionId/location"))
            .put(GET_APP_CACHE_STATUS, get("/session/:sessionId/application_cache/status"))
            .put(IS_BROWSER_ONLINE, get("/session/:sessionId/browser_connection"))
            .put(SET_BROWSER_ONLINE, post("/session/:sessionId/browser_connection"))

            .put(SWITCH_TO_CONTEXT, post("/session/:sessionId/context"))
            .put(GET_CURRENT_CONTEXT_HANDLE, get("/session/:sessionId/context"))
            .put(GET_CONTEXT_HANDLES, get("/session/:sessionId/contexts"))

            // TODO (user): Would it be better to combine this command with
            // GET_LOCAL_STORAGE_SIZE?
            .put(GET_LOCAL_STORAGE_ITEM, get("/session/:sessionId/local_storage/key/:key"))
            .put(REMOVE_LOCAL_STORAGE_ITEM, delete("/session/:sessionId/local_storage/key/:key"))
            .put(GET_LOCAL_STORAGE_KEYS, get("/session/:sessionId/local_storage"))
            .put(SET_LOCAL_STORAGE_ITEM, post("/session/:sessionId/local_storage"))
            .put(CLEAR_LOCAL_STORAGE, delete("/session/:sessionId/local_storage"))
            .put(GET_LOCAL_STORAGE_SIZE, get("/session/:sessionId/local_storage/size"))

            // TODO (user): Would it be better to combine this command with
            // GET_SESSION_STORAGE_SIZE?
            .put(GET_SESSION_STORAGE_ITEM, get("/session/:sessionId/session_storage/key/:key"))
            .put(REMOVE_SESSION_STORAGE_ITEM, delete("/session/:sessionId/session_storage/key/:key"))
            .put(GET_SESSION_STORAGE_KEYS, get("/session/:sessionId/session_storage"))
            .put(SET_SESSION_STORAGE_ITEM, post("/session/:sessionId/session_storage"))
            .put(CLEAR_SESSION_STORAGE, delete("/session/:sessionId/session_storage"))
            .put(GET_SESSION_STORAGE_SIZE, get("/session/:sessionId/session_storage/size"))

            .put(GET_SCREEN_ORIENTATION, get("/session/:sessionId/orientation"))
            .put(SET_SCREEN_ORIENTATION, post("/session/:sessionId/orientation"))

            // Interactions-related commands.
            .put(CLICK, post("/session/:sessionId/click"))
            .put(DOUBLE_CLICK, post("/session/:sessionId/doubleclick"))
            .put(MOUSE_DOWN, post("/session/:sessionId/buttondown"))
            .put(MOUSE_UP, post("/session/:sessionId/buttonup"))
            .put(MOVE_TO, post("/session/:sessionId/moveto"))
            .put(SEND_KEYS_TO_ACTIVE_ELEMENT, post("/session/:sessionId/keys"))

            // IME related commands.
            .put(IME_GET_AVAILABLE_ENGINES, get("/session/:sessionId/ime/available_engines"))
            .put(IME_GET_ACTIVE_ENGINE, get("/session/:sessionId/ime/active_engine"))
            .put(IME_IS_ACTIVATED, get("/session/:sessionId/ime/activated"))
            .put(IME_DEACTIVATE, post("/session/:sessionId/ime/deactivate"))
            .put(IME_ACTIVATE_ENGINE, post("/session/:sessionId/ime/activate"))

            // Advanced Touch API commands
            // TODO(berrada): Refactor single tap with mouse click.
            .put(TOUCH_SINGLE_TAP, post("/session/:sessionId/touch/click"))
            .put(TOUCH_DOWN, post("/session/:sessionId/touch/down"))
            .put(TOUCH_UP, post("/session/:sessionId/touch/up"))
            .put(TOUCH_MOVE, post("/session/:sessionId/touch/move"))
            .put(TOUCH_SCROLL, post("/session/:sessionId/touch/scroll"))
            .put(TOUCH_DOUBLE_TAP, post("/session/:sessionId/touch/doubleclick"))
            .put(TOUCH_LONG_PRESS, post("/session/:sessionId/touch/longclick"))
            .put(TOUCH_FLICK, post("/session/:sessionId/touch/flick"))

            .put(GET_LOG, post("/session/:sessionId/log"))
            .put(GET_AVAILABLE_LOG_TYPES, get("/session/:sessionId/log/types"))

            .put(STATUS, get("/status"));

    nameToUrl = builder.build();
}