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.dasein.cloud.zimory.ZimoryMethod.java

private @Nonnull HttpClient getClient(URI uri) throws InternalException, CloudException {
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new NoContextException();
    }//from  w ww. ja  v  a 2s .c  o  m

    boolean ssl = uri.getScheme().startsWith("https");
    int targetPort = uri.getPort();

    if (targetPort < 1) {
        targetPort = (ssl ? 443 : 80);
    }
    HttpParams params = new BasicHttpParams();

    SchemeRegistry registry = new SchemeRegistry();

    try {
        registry.register(
                new Scheme(ssl ? "https" : "http", targetPort, new X509SSLSocketFactory(new X509Store(ctx))));
    } catch (KeyManagementException e) {
        e.printStackTrace();
        throw new InternalException(e);
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
        throw new InternalException(e);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        throw new InternalException(e);
    } catch (KeyStoreException e) {
        e.printStackTrace();
        throw new InternalException(e);
    }

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    //noinspection deprecation
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setUserAgent(params, "");
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 300000);

    Properties p = ctx.getCustomProperties();

    if (p != null) {
        String proxyHost = p.getProperty("proxyHost");
        String proxyPort = p.getProperty("proxyPort");

        if (proxyHost != null) {
            int port = 0;

            if (proxyPort != null && proxyPort.length() > 0) {
                port = Integer.parseInt(proxyPort);
            }
            params.setParameter(ConnRoutePNames.DEFAULT_PROXY,
                    new HttpHost(proxyHost, port, ssl ? "https" : "http"));
        }
    }
    ClientConnectionManager ccm = new ThreadSafeClientConnManager(registry);

    return new DefaultHttpClient(ccm, params);
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.java

/**
 * Setup following elements on httpRequest:
 * <ul>/*from w ww.jav  a2 s  .c  om*/
 * <li>ConnRoutePNames.LOCAL_ADDRESS enabling IP-SPOOFING</li>
 * <li>Socket and connection timeout</li>
 * <li>Redirect handling</li>
 * <li>Keep Alive header or Connection Close</li>
 * <li>Calls setConnectionHeaders to setup headers</li>
 * <li>Calls setConnectionCookie to setup Cookie</li>
 * </ul>
 * 
 * @param url
 *            {@link URL} of the request
 * @param httpRequest
 *            http request for the request
 * @param res
 *            sample result to set cookies on
 * @throws IOException
 *             if hostname/ip to use could not be figured out
 */
protected void setupRequest(URL url, HttpRequestBase httpRequest, HTTPSampleResult res) throws IOException {

    HttpParams requestParams = httpRequest.getParams();

    // Set up the local address if one exists
    final InetAddress inetAddr = getIpSourceAddress();
    if (inetAddr != null) {// Use special field ip source address (for pseudo 'ip spoofing')
        requestParams.setParameter(ConnRoutePNames.LOCAL_ADDRESS, inetAddr);
    } else if (localAddress != null) {
        requestParams.setParameter(ConnRoutePNames.LOCAL_ADDRESS, localAddress);
    } else { // reset in case was set previously
        requestParams.removeParameter(ConnRoutePNames.LOCAL_ADDRESS);
    }

    int rto = getResponseTimeout();
    if (rto > 0) {
        requestParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, rto);
    }

    int cto = getConnectTimeout();
    if (cto > 0) {
        requestParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, cto);
    }

    requestParams.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, getAutoRedirects());

    // a well-behaved browser is supposed to send 'Connection: close'
    // with the last request to an HTTP server. Instead, most browsers
    // leave it to the server to close the connection after their
    // timeout period. Leave it to the JMeter user to decide.
    if (getUseKeepAlive()) {
        httpRequest.setHeader(HTTPConstants.HEADER_CONNECTION, HTTPConstants.KEEP_ALIVE);
    } else {
        httpRequest.setHeader(HTTPConstants.HEADER_CONNECTION, HTTPConstants.CONNECTION_CLOSE);
    }

    setConnectionHeaders(httpRequest, url, getHeaderManager(), getCacheManager());

    String cookies = setConnectionCookie(httpRequest, url, getCookieManager());

    if (res != null) {
        res.setCookies(cookies);
    }

}

From source file:com.akop.bach.parser.PsnUsParser.java

public PsnUsParser(Context context) {
    super(context);

    HttpParams params = mHttpClient.getParams();
    //params.setParameter("http.useragent", USER_AGENT);
    params.setParameter("http.protocol.max-redirects", 0);
}

From source file:com.benefit.buy.library.http.query.callback.AbstractAjaxCallback.java

private void httpDo(HttpUriRequest hr, String url, Map<String, String> headers, AjaxStatus status)
        throws ClientProtocolException, IOException {
    if (AGENT != null) {
        hr.addHeader("User-Agent", AGENT);
    }/*from  w w w  . j av  a2s . c  o m*/
    if (headers != null) {
        for (String name : headers.keySet()) {
            hr.addHeader(name, headers.get(name));
        }
    }
    if (GZIP && ((headers == null) || !headers.containsKey("Accept-Encoding"))) {
        hr.addHeader("Accept-Encoding", "gzip");
    }
    String cookie = makeCookie();
    if (cookie != null) {
        hr.addHeader("Cookie", cookie);
    }
    if (ah != null) {
        ah.applyToken(this, hr);
    }
    DefaultHttpClient client = getClient();
    HttpParams hp = hr.getParams();
    if (proxy != null) {
        hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }
    if (timeout > 0) {
        hp.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
        hp.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
    }
    HttpContext context = new BasicHttpContext();
    //        CookieStore cookieStore = new BasicCookieStore();
    //        context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    request = hr;
    if (abort) {
        throw new IOException("Aborted");
    }
    HttpResponse response = null;
    try {
        //response = client.execute(hr, context);
        response = execute(hr, client, context);
        getCookie(client);
    } catch (HttpHostConnectException e) {
        //if proxy is used, automatically retry without proxy
        if (proxy != null) {
            AQUtility.debug("proxy failed, retrying without proxy");
            hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, null);
            //response = client.execute(hr, context);
            response = execute(hr, client, context);
        } else {
            throw e;
        }
    }
    byte[] data = null;
    String redirect = url;
    int code = response.getStatusLine().getStatusCode();
    String message = response.getStatusLine().getReasonPhrase();
    String error = null;
    HttpEntity entity = response.getEntity();
    File file = null;
    if ((code < 200) || (code >= 300)) {
        InputStream is = null;
        try {
            if (entity != null) {
                is = entity.getContent();
                byte[] s = toData(getEncoding(entity), is);
                error = new String(s, "UTF-8");
                AQUtility.debug("error", error);
            }
        } catch (Exception e) {
            AQUtility.debug(e);
        } finally {
            AQUtility.close(is);
        }
    } else {
        HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
        redirect = currentHost.toURI() + currentReq.getURI();
        int size = Math.max(32, Math.min(1024 * 64, (int) entity.getContentLength()));
        OutputStream os = null;
        InputStream is = null;
        try {
            file = getPreFile();
            if (file == null) {
                os = new PredefinedBAOS(size);
            } else {
                file.createNewFile();
                os = new BufferedOutputStream(new FileOutputStream(file));
            }
            is = entity.getContent();
            if ("gzip".equalsIgnoreCase(getEncoding(entity))) {
                is = new GZIPInputStream(is);
            }
            copy(is, os, (int) entity.getContentLength());
            os.flush();
            if (file == null) {
                data = ((PredefinedBAOS) os).toByteArray();
            } else {
                if (!file.exists() || (file.length() == 0)) {
                    file = null;
                }
            }
        } finally {
            AQUtility.close(is);
            AQUtility.close(os);
        }
    }
    AQUtility.debug("response", code);
    if (data != null) {
        AQUtility.debug(data.length, url);
    }
    status.code(code).message(message).error(error).redirect(redirect).time(new Date()).data(data).file(file)
            .client(client).context(context).headers(response.getAllHeaders());
}

From source file:com.zoffcc.applications.aagtl.HTMLDownloader.java

public boolean login() {
    // System.out.println("--L--- LOGIN START -----");

    String login_url = "https://www.geocaching.com/login/default.aspx";

    DefaultHttpClient client2 = null;//from w  w  w  .j  a  va 2  s.c  om
    HttpHost proxy = null;

    if (CacheDownloader.DEBUG2_) {
        // NEVER enable this on a production release!!!!!!!!!!
        // NEVER enable this on a production release!!!!!!!!!!
        trust_Every_ssl_cert();

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

        HttpParams params = new BasicHttpParams();
        params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
        params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
        params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);

        proxy = new HttpHost("192.168.0.1", 8888);
        params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

        ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);
        client2 = new DefaultHttpClient(cm, params);
        // NEVER enable this on a production release!!!!!!!!!!
        // NEVER enable this on a production release!!!!!!!!!!
    } else {
        HttpParams httpParameters = new BasicHttpParams();
        int timeoutConnection = 10000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        int timeoutSocket = 10000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        client2 = new DefaultHttpClient(httpParameters);
    }

    if (CacheDownloader.DEBUG2_) {
        client2.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    // read first page to check for login
    // read first page to check for login
    // read first page to check for login

    String websiteData2 = null;
    URI uri2 = null;
    try {
        uri2 = new URI(login_url);
    } catch (URISyntaxException e) {
        e.printStackTrace();
        return false;
    }

    client2.setCookieStore(cookie_jar);

    HttpGet method2 = new HttpGet(uri2);

    method2.addHeader("User-Agent",
            "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.1.10) Gecko/20071115 Firefox/2.0.0.10");
    method2.addHeader("Pragma", "no-cache");
    method2.addHeader("Accept-Language", "en");

    HttpResponse res = null;
    try {
        res = client2.execute(method2);
    } catch (ClientProtocolException e1) {
        e1.printStackTrace();
        return false;
    } catch (IOException e1) {
        e1.printStackTrace();
        return false;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }

    InputStream data = null;
    try {
        data = res.getEntity().getContent();
    } catch (IllegalStateException e1) {
        e1.printStackTrace();
        return false;
    } catch (IOException e1) {
        e1.printStackTrace();
        return false;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }

    websiteData2 = generateString(data);

    if (CacheDownloader.DEBUG_)
        System.out.println("111 cookies=" + dumpCookieStore(client2.getCookieStore()));
    cookie_jar = client2.getCookieStore();

    // on every page
    final Matcher matcherLogged2In = patternLogged2In.matcher(websiteData2);
    if (matcherLogged2In.find()) {
        if (CacheDownloader.DEBUG_)
            System.out.println("login: -> already logged in (1)");
        return true;
    }

    // after login
    final Matcher matcherLoggedIn = patternLoggedIn.matcher(websiteData2);
    if (matcherLoggedIn.find()) {
        if (CacheDownloader.DEBUG_)
            System.out.println("login: -> already logged in (2)");
        return true;
    }
    // read first page to check for login
    // read first page to check for login
    // read first page to check for login

    // ok post login data as formdata
    // ok post login data as formdata
    // ok post login data as formdata
    // ok post login data as formdata
    HttpPost method = new HttpPost(uri2);

    method.addHeader("User-Agent", "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0) Firefox/7.0");
    method.addHeader("Pragma", "no-cache");
    method.addHeader("Content-Type", "application/x-www-form-urlencoded");
    method.addHeader("Accept-Language", "en");

    List<NameValuePair> loginInfo = new ArrayList<NameValuePair>();

    loginInfo.add(new BasicNameValuePair("__EVENTTARGET", ""));
    loginInfo.add(new BasicNameValuePair("__EVENTARGUMENT", ""));

    String[] viewstates = getViewstates(websiteData2);
    if (CacheDownloader.DEBUG_)
        System.out.println("vs==" + viewstates[0]);
    putViewstates(loginInfo, viewstates);

    loginInfo.add(new BasicNameValuePair("ctl00$ContentBody$tbUsername",
            this.main_aagtl.global_settings.options_username));
    loginInfo.add(new BasicNameValuePair("ctl00$ContentBody$tbPassword",
            this.main_aagtl.global_settings.options_password));
    loginInfo.add(new BasicNameValuePair("ctl00$ContentBody$btnSignIn", "Login"));
    loginInfo.add(new BasicNameValuePair("ctl00$ContentBody$cbRememberMe", "on"));

    //for (int i = 0; i < loginInfo.size(); i++)
    //{
    //   System.out.println("x*X " + loginInfo.get(i).getName() + " " + loginInfo.get(i).getValue());
    //}

    // set cookies
    client2.setCookieStore(cookie_jar);

    HttpEntity entity = null;
    try {
        entity = new UrlEncodedFormEntity(loginInfo, HTTP.UTF_8);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return false;
    }

    //      try
    //      {
    //         System.out.println("1 " + entity.toString());
    //         InputStream in2 = entity.getContent();
    //         InputStreamReader ir2 = new InputStreamReader(in2, "utf-8");
    //         BufferedReader r = new BufferedReader(ir2);
    //         System.out.println("line=" + r.readLine());
    //      }
    //      catch (Exception e2)
    //      {
    //         e2.printStackTrace();
    //      }

    method.setEntity(entity);

    HttpResponse res2 = null;
    try {
        res2 = client2.execute(method);
        if (CacheDownloader.DEBUG_)
            System.out.println("login response ->" + String.valueOf(res2.getStatusLine()));
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }

    //      for (int x = 0; x < res2.getAllHeaders().length; x++)
    //      {
    //         System.out.println("## n=" + res2.getAllHeaders()[x].getName());
    //         System.out.println("## v=" + res2.getAllHeaders()[x].getValue());
    //      }

    InputStream data2 = null;
    try {
        data2 = res2.getEntity().getContent();
    } catch (IllegalStateException e1) {
        e1.printStackTrace();
        return false;
    } catch (IOException e1) {
        e1.printStackTrace();
        return false;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }

    websiteData2 = generateString(data2);

    if (CacheDownloader.DEBUG_)
        System.out.println("2222 cookies=" + dumpCookieStore(client2.getCookieStore()));
    cookie_jar = client2.getCookieStore();

    String[] viewstates2 = getViewstates(websiteData2);
    if (CacheDownloader.DEBUG_)
        System.out.println("vs==" + viewstates2[0]);

    //      System.out.println("******");
    //      System.out.println("******");
    //      System.out.println("******");
    //      System.out.println(websiteData2);
    //      System.out.println("******");
    //      System.out.println("******");
    //      System.out.println("******");

    return true;

}

From source file:org.dasein.cloud.azure.AzureMethod.java

protected @Nonnull HttpClient getClient() throws CloudException, InternalException {
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new AzureConfigException("No context was defined for this request");
    }//from   www  .  j  av  a2s  .c  om
    String endpoint = ctx.getEndpoint();

    if (endpoint == null) {
        throw new AzureConfigException("No cloud endpoint was defined");
    }
    boolean ssl = endpoint.startsWith("https");
    int targetPort;

    try {
        URI uri = new URI(endpoint);

        targetPort = uri.getPort();
        if (targetPort < 1) {
            targetPort = (ssl ? 443 : 80);
        }
    } catch (URISyntaxException e) {
        throw new AzureConfigException(e);
    }
    HttpParams params = new BasicHttpParams();
    SchemeRegistry registry = new SchemeRegistry();

    try {
        registry.register(
                new Scheme(ssl ? "https" : "http", targetPort, new AzureSSLSocketFactory(new AzureX509(ctx))));
    } catch (KeyManagementException e) {
        e.printStackTrace();
        throw new InternalException(e);
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
        throw new InternalException(e);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        throw new InternalException(e);
    } catch (KeyStoreException e) {
        e.printStackTrace();
        throw new InternalException(e);
    }

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setUserAgent(params, "Dasein Cloud");
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 300000);

    Properties p = ctx.getCustomProperties();

    if (p != null) {
        String proxyHost = p.getProperty("proxyHost");
        String proxyPort = p.getProperty("proxyPort");

        if (proxyHost != null) {
            int port = 0;

            if (proxyPort != null && proxyPort.length() > 0) {
                port = Integer.parseInt(proxyPort);
            }
            params.setParameter(ConnRoutePNames.DEFAULT_PROXY,
                    new HttpHost(proxyHost, port, ssl ? "https" : "http"));
        }
    }

    ClientConnectionManager ccm = new ThreadSafeClientConnManager(registry);

    return new DefaultHttpClient(ccm, params);
}

From source file:com.pmi.restlet.ext.httpclient.HttpClientHelper.java

/**
 * Configures the various parameters of the connection manager and the HTTP
 * client.//from   w  w  w  . j a  v  a 2s.  co  m
 *
 * @param params
 *            The parameter list to update.
 */
protected void configure(HttpParams params) {
    ConnManagerParams.setMaxTotalConnections(params, getMaxTotalConnections());
    ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(getMaxConnectionsPerHost()));

    // Configure other parameters
    HttpClientParams.setAuthenticating(params, false);
    HttpClientParams.setRedirecting(params, isFollowRedirects());
    HttpClientParams.setCookiePolicy(params, CookiePolicy.BROWSER_COMPATIBILITY);
    HttpConnectionParams.setTcpNoDelay(params, getTcpNoDelay());
    HttpConnectionParams.setConnectionTimeout(params, getConnectTimeout());
    HttpConnectionParams.setSoTimeout(params, getSocketTimeout());
    params.setIntParameter(ClientPNames.MAX_REDIRECTS, getMaxRedirects());

    //-Dhttp.proxyHost=chlaubc.obs.pmi -Dhttp.proxyPort=8000 -Dhttp.nonProxyHosts=localhost|127.0.0.1|*.app.pmi
    String httpProxyHost = getProxyHost();
    if (httpProxyHost != null) {
        if (StringUtils.isNotEmpty(getNonProxyHosts())) {
            System.setProperty("http.nonProxyHosts", getNonProxyHosts());
        } else {
            System.getProperties().remove("http.nonProxyHosts");
        }
        System.setProperty("http.proxyPort", String.valueOf(getProxyPort()));
        System.setProperty("http.proxyHost", httpProxyHost);
        HttpHost proxy = new HttpHost(httpProxyHost, getProxyPort());
        params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

    }
}

From source file:org.dasein.cloud.rackspace.AbstractMethod.java

private @Nonnull HttpClient getClient() throws CloudException {
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new CloudException("No context was provided for this request");
    }//from   w  ww  .j a  v  a  2s. com
    String endpoint = ctx.getEndpoint();
    boolean ssl = (endpoint != null && endpoint.startsWith("https"));
    HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    //noinspection deprecation
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setUserAgent(params, "Dasein Cloud");

    Properties p = ctx.getCustomProperties();

    if (p != null) {
        String proxyHost = p.getProperty("proxyHost");
        String proxyPort = p.getProperty("proxyPort");

        if (proxyHost != null) {
            int port = 0;

            if (proxyPort != null && proxyPort.length() > 0) {
                port = Integer.parseInt(proxyPort);
            }
            params.setParameter(ConnRoutePNames.DEFAULT_PROXY,
                    new HttpHost(proxyHost, port, ssl ? "https" : "http"));
        }
    }
    return new DefaultHttpClient(params);
}