Example usage for org.apache.http.client HttpClient getParams

List of usage examples for org.apache.http.client HttpClient getParams

Introduction

In this page you can find the example usage for org.apache.http.client HttpClient getParams.

Prototype

@Deprecated
HttpParams getParams();

Source Link

Document

Obtains the parameters for this client.

Usage

From source file:ch.entwine.weblounge.preview.xhtmlrenderer.XhtmlRendererPagePreviewGenerator.java

/**
 * Renders the page located at <code>rendererURL</code> in the given language.
 * //w  w  w.  j a  v  a  2s. c  o  m
 * @param rendererURL
 *          the page url
 * @param site
 *          the site
 * @param environment
 *          the environment
 * @param language
 *          the language
 * @param version
 *          the version
 * @return the rendered <code>HTML</code>
 * @throws ServletException
 *           if rendering fails
 * @throws IOException
 *           if reading from the servlet fails
 */
private String render(URL rendererURL, Site site, Environment environment, Language language, long version)
        throws ServletException, IOException {
    Servlet servlet = siteServlets.get(site.getIdentifier());

    String httpContextURI = UrlUtils.concat("/weblounge-sites", site.getIdentifier());
    int httpContextURILength = httpContextURI.length();
    String url = rendererURL.toExternalForm();
    int uriInPath = url.indexOf(httpContextURI);

    // Are we trying to render a site resource (e. g. a jsp during
    // precompilation)?
    if (uriInPath > 0) {
        String pathInfo = url.substring(uriInPath + httpContextURILength);

        // Prepare the mock request
        MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
        request.setServerName(site.getHostname(environment).getURL().getHost());
        request.setServerPort(site.getHostname(environment).getURL().getPort());
        request.setMethod(site.getHostname(environment).getURL().getProtocol());
        request.setAttribute(WebloungeRequest.LANGUAGE, language);
        request.setPathInfo(pathInfo);
        request.setRequestURI(UrlUtils.concat(httpContextURI, pathInfo));

        MockHttpServletResponse response = new MockHttpServletResponse();
        servlet.service(request, response);
        return response.getContentAsString();
    } else {
        HttpClient httpClient = new DefaultHttpClient();
        httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);
        try {
            if (version == Resource.WORK) {
                rendererURL = new URL(UrlUtils.concat(rendererURL.toExternalForm(),
                        "work_" + language.getIdentifier() + ".html"));
            } else {
                rendererURL = new URL(UrlUtils.concat(rendererURL.toExternalForm(),
                        "index_" + language.getIdentifier() + ".html"));
            }
            HttpGet getRequest = new HttpGet(rendererURL.toExternalForm());
            getRequest.addHeader(new BasicHeader("X-Weblounge-Special", "Page-Preview"));
            HttpResponse response = httpClient.execute(getRequest);
            if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK)
                return null;
            String responseText = EntityUtils.toString(response.getEntity(), "utf-8");
            return responseText;
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
    }
}

From source file:com.foundationdb.http.HttpMonitorVerifySSLIT.java

/**
 * This code sets up the httpclient to accept any SSL certificate. The 
 * SSL certificate generated by the instructions above is not correctly
 * signed, so we need ignore the problem. 
 * This code should not, under any circumstances, be allowed anywhere 
 * the production code. /* w  w w. jav  a2 s  .c om*/
 * @param base
 * @return
 */
private HttpClient wrapClient(HttpClient base) {
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");

        ctx.init(null, new TrustManager[] { getTrustManager() }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, 8091));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:com.google.appinventor.components.runtime.FusiontablesControl.java

private IClientLoginHelper createClientLoginHelper(String accountPrompt, String service) {
    if (SdkLevel.getLevel() >= SdkLevel.LEVEL_ECLAIR) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpConnectionParams.setSoTimeout(httpClient.getParams(), SERVER_TIMEOUT_MS);
        HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), SERVER_TIMEOUT_MS);
        return new ClientLoginHelper(activity, service, accountPrompt, httpClient);
    }/*from   w  w  w. j a  v  a 2s . c om*/
    return null;
}

From source file:net.vivekiyer.GAL.ActiveSyncManager.java

/**
 * @return the HttpClient object/*from   www. j  a  v a  2 s. co m*/
 * 
 * Creates a HttpClient object that is used to POST messages to the Exchange server
 */
private HttpClient createHttpClient() {
    HttpParams httpParams = new BasicHttpParams();

    // Turn off stale checking.  Our connections break all the time anyway,
    // and it's not worth it to pay the penalty of checking every time.
    HttpConnectionParams.setStaleCheckingEnabled(httpParams, false);

    // Default connection and socket timeout of 120 seconds.  Tweak to taste.
    HttpConnectionParams.setConnectionTimeout(httpParams, 120 * 1000);
    HttpConnectionParams.setSoTimeout(httpParams, 120 * 1000);
    HttpConnectionParams.setSocketBufferSize(httpParams, 131072);

    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", new PlainSocketFactory(), 80));
    registry.register(new Scheme("https",
            mAcceptAllCerts ? new FakeSocketFactory() : SSLSocketFactory.getSocketFactory(), 443));
    HttpClient httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, registry),
            httpParams);

    // Set the headers
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Android");

    // Make sure we are not validating any hostnames
    SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
    sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    return httpclient;
}

From source file:org.cimmyt.dnast.service.imp.FileRepositoryServiceClientImp.java

/**
 * Checks if the connection to Knowledge Base is available, if there is, configures it.
 * @return A flag indicating if there is communication with Knowledge Base services
 *//*from  w  w w. j  av a  2  s.  c o  m*/
@Override
public boolean isServiceAvailable() {
    if (proxy == null) {
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpParams params = httpClient.getParams();

            HttpConnectionParams.setConnectionTimeout(params,
                    Integer.parseInt(prop.getKey("service.kbase.connectionTimeout", Bundle.conf)));
            HttpConnectionParams.setSoTimeout(params,
                    Integer.parseInt(prop.getKey("service.kbase.socketTimeout", Bundle.conf)));

            ClientExecutor executor = new ApacheHttpClient4Executor(httpClient);

            proxy = ProxyFactory.create(KBaseQueryService.class, prop.getKey("service.kbase.url", Bundle.conf),
                    executor);
            proxy.getSchemaList(endpoint).getEntity();
        } catch (Exception e) {
            proxy = null;
            //e.printStackTrace();
            System.out.println("KBServices not available.");
        }
    }
    return proxy != null;
}

From source file:com.xorcode.andtweet.net.ConnectionBasicAuth.java

/**
 * Execute a GET request against the Twitter REST API.
 * //from  w  ww  .ja v  a 2s . co m
 * @param url
 * @param client
 * @return String
 * @throws ConnectionException
 */
private String getRequest(String url, HttpClient client) throws ConnectionException {
    String result = null;
    int statusCode = 0;
    HttpGet getMethod = new HttpGet(url);
    try {
        getMethod.setHeader("User-Agent", USER_AGENT);
        getMethod.addHeader("Authorization", "Basic " + getCredentials());
        client.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT,
                DEFAULT_GET_REQUEST_TIMEOUT);
        client.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, DEFAULT_GET_REQUEST_TIMEOUT);
        HttpResponse httpResponse = client.execute(getMethod);
        statusCode = httpResponse.getStatusLine().getStatusCode();
        result = retrieveInputStream(httpResponse.getEntity());
    } catch (Exception e) {
        Log.e(TAG, "getRequest: " + e.toString());
        throw new ConnectionException(e);
    } finally {
        getMethod.abort();
    }
    parseStatusCode(statusCode, url);
    return result;
}

From source file:com.drive.student.xutils.HttpUtils.java

/**
 *
 * HttpClient??post?./*from  w  w  w . java 2 s.  c o m*/
 */
public HttpResponse sendHttpPost(String url, Map<String, String> params, boolean isGzip) {
    try {
        List<NameValuePair> param = new ArrayList<NameValuePair>(); // ?
        if (params != null) {
            for (Entry<String, String> entry : params.entrySet()) {
                param.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
        HttpPost request = new HttpPost(url);
        buildHttpHeaderForPost(request);// 
        if (isGzip) {
            request.addHeader("accept-encoding", "gzip");
        }
        HttpEntity entity = new UrlEncodedFormEntity(param, "UTF-8");
        request.setEntity(entity);
        HttpClient client = new DefaultHttpClient();

        client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                HttpUtils.DEFAULT_CONN_TIMEOUT); // 
        client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, HttpUtils.DEFAULT_SO_TIMEOUT); // ?
        HttpResponse response = client.execute(request, httpContext);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            LogUtil.e("hxk", "upload file success -->>");
            return response;
        } else {
            LogUtil.e("hxk", "upload fail -->>" + response.getStatusLine().getStatusCode());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    LogUtil.e("hxk", "upload fail -->>");
    return null;
}

From source file:com.drive.student.xutils.HttpUtils.java

/**
 * HttpClient??get?.//from  w w  w  .  j  av a2s .  c om
 */
public HttpResponse sendHttpGet(String url, Map params, boolean isGzip) {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
            HttpUtils.DEFAULT_CONN_TIMEOUT); // 
    httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, HttpUtils.DEFAULT_SO_TIMEOUT); // ?

    /* HTTPGet */
    String paramStr = "";
    if (params != null) {
        for (Object o : params.entrySet()) {
            Entry entry = (Entry) o;
            Object key = entry.getKey();
            Object val = entry.getValue();
            paramStr += paramStr = "&" + key + "=" + val;
        }
    }
    if (!paramStr.equals("")) {
        paramStr = paramStr.replaceFirst("&", "?");
        url += paramStr;
    }
    HttpGet request = new HttpGet(url);
    buildHttpHeaderForGet(request);// 
    if (isGzip) {
        request.addHeader("accept-encoding", "gzip");
    }
    try {
        /* ??? */
        HttpResponse response = httpclient.execute(request, httpContext);
        /* ??200 ok */
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return response;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.kuali.mobility.open311.controllers.Open311Controller.java

@RequestMapping(value = "/servicePost", method = RequestMethod.POST)
public String submitService(Model uiModel, HttpServletRequest request,
        @ModelAttribute("service") Service service, BindingResult result) {

    if (isValidService(service, result)) {

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

        String serviceURL = "https://bloomington.in.gov/test/open311/v2/requests.xml";

        final HttpClient client = new DefaultHttpClient();
        HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
        HttpResponse response;// w w  w . ja  v a  2 s.  co m

        try {

            pairs.add(new BasicNameValuePair("api_key", "5012e4acc3618"));
            pairs.add(new BasicNameValuePair("jurisdiction_id", "bloomington.in.gov"));
            pairs.add(new BasicNameValuePair("service_code", service.getResponseServiceCode()));
            pairs.add(new BasicNameValuePair("lat", service.getLatitude()));
            pairs.add(new BasicNameValuePair("long", service.getLongitude()));

            if (!(service.getAddressString() == null || "".equals(service.getAddressString().trim()))) {
                pairs.add(new BasicNameValuePair("address_string", service.getAddressString()));
            }

            if (!(service.getEmail() == null || "".equals(service.getEmail().trim()))) {
                pairs.add(new BasicNameValuePair("email", service.getEmail()));
            }

            if (!(service.getFname() == null || "".equals(service.getFname().trim()))) {
                pairs.add(new BasicNameValuePair("first_name", service.getFname()));
            }

            if (!(service.getLname() == null || "".equals(service.getLname().trim()))) {
                pairs.add(new BasicNameValuePair("last_name", service.getLname()));
            }

            if (!(service.getPhone() == null || "".equals(service.getPhone().trim()))) {
                pairs.add(new BasicNameValuePair("phone", service.getPhone()));
            }

            if (!(service.getDescription() == null || "".equals(service.getDescription().trim()))) {
                pairs.add(new BasicNameValuePair("description", service.getDescription()));
            }

            if (!(service.getAttributes() == null)) {
                for (int j = 0; j < service.getAttributes().size(); j++) {
                    if (service.getAttributes().get(j).getType().equalsIgnoreCase("multivaluelist")) {
                        String values[] = service.getAttributes().get(j).getValue().split(",");
                        for (String s : values) {
                            pairs.add(new BasicNameValuePair(
                                    "attribute[" + service.getAttributes().get(j).getKey() + "]", s));
                        }
                    } else {
                        pairs.add(new BasicNameValuePair(
                                "attribute[" + service.getAttributes().get(j).getKey() + "]",
                                service.getAttributes().get(j).getValue()));
                    }
                }
            }

            final HttpPost post1 = new HttpPost(serviceURL);
            post1.setEntity(new UrlEncodedFormEntity(pairs));

            response = client.execute(post1);

        } catch (Exception e) {
        }

        return "incident/thanks";
    } else {
        return "open311/service";
    }
}