Example usage for org.apache.http.impl.conn SingleClientConnManager SingleClientConnManager

List of usage examples for org.apache.http.impl.conn SingleClientConnManager SingleClientConnManager

Introduction

In this page you can find the example usage for org.apache.http.impl.conn SingleClientConnManager SingleClientConnManager.

Prototype

@Deprecated
public SingleClientConnManager(final HttpParams params, final SchemeRegistry schreg) 

Source Link

Document

Creates a new simple connection manager.

Usage

From source file:neembuu.release1.httpclient.NHttpClient.java

public static DefaultHttpClient getNewInstance() {
    DefaultHttpClient new_httpClient = null;
    new_httpClient = new DefaultHttpClient();
    GlobalTestSettings.ProxySettings proxySettings = GlobalTestSettings.getGlobalProxySettings();
    HttpContext context = new BasicHttpContext();
    SchemeRegistry schemeRegistry = new SchemeRegistry();

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

    try {//from   w  w w  .j  a  v a2 s.  c  o m
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        schemeRegistry.register(new Scheme("https", new SSLSocketFactory(keyStore), 8080));
    } catch (Exception a) {
        a.printStackTrace(System.err);
    }

    context.setAttribute(ClientContext.SCHEME_REGISTRY, schemeRegistry);
    context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY,
            new BasicScheme()/*file.httpClient.getAuthSchemes()*/);

    context.setAttribute(ClientContext.COOKIESPEC_REGISTRY,
            new_httpClient.getCookieSpecs()/*file.httpClient.getCookieSpecs()*/
    );

    BasicCookieStore basicCookieStore = new BasicCookieStore();

    context.setAttribute(ClientContext.COOKIE_STORE, basicCookieStore/*file.httpClient.getCookieStore()*/);
    context.setAttribute(ClientContext.CREDS_PROVIDER,
            new BasicCredentialsProvider()/*file.httpClient.getCredentialsProvider()*/);

    HttpConnection hc = new DefaultHttpClientConnection();
    context.setAttribute(ExecutionContext.HTTP_CONNECTION, hc);

    //System.out.println(file.httpClient.getParams().getParameter("http.useragent"));
    HttpParams httpParams = new BasicHttpParams();

    if (proxySettings != null) {
        AuthState as = new AuthState();
        as.setCredentials(new UsernamePasswordCredentials(proxySettings.userName, proxySettings.password));
        as.setAuthScope(AuthScope.ANY);
        as.setAuthScheme(new BasicScheme());
        httpParams.setParameter(ClientContext.PROXY_AUTH_STATE, as);
        httpParams.setParameter("http.proxy_host", new HttpHost(proxySettings.host, proxySettings.port));
    }

    new_httpClient = new DefaultHttpClient(
            new SingleClientConnManager(httpParams/*file.httpClient.getParams()*/, schemeRegistry),
            httpParams/*file.httpClient.getParams()*/);

    if (proxySettings != null) {
        new_httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(proxySettings.userName, proxySettings.password));
    }

    return new_httpClient;
}

From source file:cvut.fel.mobilevoting.murinrad.communications.Connection.java

/**
 * Initializes the HTTP connection/*from   w  w  w.  j a  v a 2 s . c om*/
 */
public void InitializeUnsecure() {

    try {
        run = false;
        port = server.getPort();
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, 3000);
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        schemeRegistry = new SchemeRegistry();

        Scheme http = new Scheme("http", new PlainSocketFactory(), port);

        schemeRegistry.register(http);

        HttpPost post = new HttpPost(server.getAddress());
        SingleClientConnManager cm = new SingleClientConnManager(post.getParams(), schemeRegistry);

        connection = new DefaultHttpClient(cm, params);
        this.connection.addResponseInterceptor(new Interceptor(this));
        notifyOfProggress();
        postAndRecieve("OPTIONS", "/", null, null, true);
        // notifyOfProggress(false);
        instance = this;

    } catch (IllegalStateException ex) {

    } catch (Exception ex) {
        Log.e("Android mobile voting", "INIT HTTP error " + ex.toString());
        showNoConError();

    }

}

From source file:com.villemos.ispace.webster.WebsterProducer.java

public void process(Exchange exchange) throws Exception {

    /** Always ignore authentication protocol errors. */
    if (ignoreAuthenticationFailure) {
        SSLContext sslContext = SSLContext.getInstance("SSL");

        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new EasyX509TrustManager() }, new SecureRandom());

        SchemeRegistry schemeRegistry = new SchemeRegistry();

        SSLSocketFactory sf = new SSLSocketFactory(sslContext);
        Scheme httpsScheme = new Scheme("https", sf, 443);
        schemeRegistry.register(httpsScheme);

        SocketFactory sfa = new PlainSocketFactory();
        Scheme httpScheme = new Scheme("http", sfa, 80);
        schemeRegistry.register(httpScheme);

        HttpParams params = new BasicHttpParams();
        ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);

        client = new DefaultHttpClient(cm, params);
    } else {/*from www.j  a  va2  s.  c  o  m*/
        client = new DefaultHttpClient();
    }

    String proxyHost = getWebsterEndpoint().getProxyHost();
    Integer proxyPort = getWebsterEndpoint().getProxyPort();

    if (proxyHost != null && proxyPort != null) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    } else {
        ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
        client.setRoutePlanner(routePlanner);
    }

    /** The target location may demand authentication. We setup preemptive authentication. */
    if (getWebsterEndpoint().getAuthenticationUser() != null
            && getWebsterEndpoint().getAuthenticationPassword() != null) {
        client.getCredentialsProvider().setCredentials(
                new AuthScope(getWebsterEndpoint().getDomain(), getWebsterEndpoint().getPort()),
                new UsernamePasswordCredentials(getWebsterEndpoint().getAuthenticationUser(),
                        getWebsterEndpoint().getAuthenticationPassword()));
    }

    /** Set default cookie policy and store. Can be overridden for a specific method using for example;
     *    method.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); 
     */
    client.setCookieStore(cookieStore);
    client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

    String uriStr = getWebsterEndpoint().getProtocol() + "://" + getWebsterEndpoint().getDomain() + "/"
            + getWebsterEndpoint().getPath();
    if (getWebsterEndpoint().getPort() != 80) {
        uriStr += ":" + getWebsterEndpoint().getPort() + "/" + getWebsterEndpoint().getPath();
    }

    /** Break the query into its elements and search for each. */
    for (String word : ((String) exchange.getIn().getHeader(SolrOptions.query)).split("\\s+")) {
        uriStr += "/" + word;
        URI uri = new URI(uriStr);

        if (getWebsterEndpoint().getPort() != 80) {
            target = new HttpHost(getWebsterEndpoint().getDomain(), getWebsterEndpoint().getPort(),
                    getWebsterEndpoint().getProtocol());
        } else {
            target = new HttpHost(getWebsterEndpoint().getDomain());
        }
        localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        HttpUriRequest method = new HttpGet(uri);
        HttpResponse response = client.execute(target, method, localContext);

        if (response.getStatusLine().getStatusCode() == 200) {
            /** Extract result. */
            String page = HttpClientConfigurer.readFully(response.getEntity().getContent());

            ResultSet set = new ResultSet();

            Matcher matcher = pattern.matcher(page);
            if (matcher.find()) {
                String result = matcher.group(1).replaceAll("\\<.*?\\>", "").replaceAll("\\s+", " ");

                /** Create ResultSet*/
                InformationObject io = new InformationObject();
                io.hasUri = uriStr;
                io.fromSource = "Webster";
                io.hasTitle = "Webster definition of '" + word + "'.";
                io.ofEntityType = "Definition";
                io.ofMimeType = "text/html";
                io.withRawText = result;
                io.score = 20;
                set.informationobjects.add(io);
            }

            matcher = spellPattern.matcher(page);
            if (matcher.find()) {
                String result = matcher.group(1);
                String[] elements = result.split("<li><a href=.*?>");

                for (String element : elements) {
                    if (element.trim().equals("") == false) {
                        set.suggestions
                                .add(new Suggestion(word, element.replaceAll("<.*?>", "").trim(), "Webster"));
                    }
                }
            }

            if (exchange.getIn().getHeader(SolrOptions.stream) != null) {

                for (InformationObject io : set.informationobjects) {
                    Exchange newExchange = new DefaultExchange(endpoint.getCamelContext());
                    newExchange.getIn().setBody(io);
                    endpoint.getCamelContext().createProducerTemplate()
                            .send((String) exchange.getIn().getHeader(SolrOptions.stream), newExchange);
                }

                for (Suggestion suggestion : set.suggestions) {
                    Exchange newExchange = new DefaultExchange(endpoint.getCamelContext());
                    newExchange.getIn().setBody(suggestion);
                    endpoint.getCamelContext().createProducerTemplate()
                            .send((String) exchange.getIn().getHeader(SolrOptions.stream), newExchange);
                }
            } else {
                exchange.getOut().setBody(set);
            }
        } else {
            HttpEntity entity = response.getEntity();
            InputStream instream = entity.getContent();
            String page = HttpClientConfigurer.readFully(response.getEntity().getContent());

            System.out.println(page);
        }
    }
}

From source file:neembuu.vfs.test.FileNameAndSizeFinderService.java

private DefaultHttpClient newClient() {
    DefaultHttpClient client = new DefaultHttpClient();
    GlobalTestSettings.ProxySettings proxySettings = GlobalTestSettings.getGlobalProxySettings();
    HttpContext context = new BasicHttpContext();
    SchemeRegistry schemeRegistry = new SchemeRegistry();

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

    try {//from   ww w . j  a  v a 2 s. com
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        schemeRegistry.register(new Scheme("https", new SSLSocketFactory(keyStore), 8080));
    } catch (Exception a) {
        a.printStackTrace(System.err);
    }

    context.setAttribute(ClientContext.SCHEME_REGISTRY, schemeRegistry);
    context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY,
            new BasicScheme()/*file.httpClient.getAuthSchemes()*/);

    context.setAttribute(ClientContext.COOKIESPEC_REGISTRY,
            client.getCookieSpecs()/*file.httpClient.getCookieSpecs()*/
    );

    BasicCookieStore basicCookieStore = new BasicCookieStore();

    context.setAttribute(ClientContext.COOKIE_STORE, basicCookieStore/*file.httpClient.getCookieStore()*/);
    context.setAttribute(ClientContext.CREDS_PROVIDER,
            new BasicCredentialsProvider()/*file.httpClient.getCredentialsProvider()*/);

    HttpConnection hc = new DefaultHttpClientConnection();
    context.setAttribute(ExecutionContext.HTTP_CONNECTION, hc);

    //System.out.println(file.httpClient.getParams().getParameter("http.useragent"));
    HttpParams httpParams = new BasicHttpParams();

    if (proxySettings != null) {
        AuthState as = new AuthState();
        as.setCredentials(new UsernamePasswordCredentials(proxySettings.userName, proxySettings.password));
        as.setAuthScope(AuthScope.ANY);
        as.setAuthScheme(new BasicScheme());
        httpParams.setParameter(ClientContext.PROXY_AUTH_STATE, as);
        httpParams.setParameter("http.proxy_host", new HttpHost(proxySettings.host, proxySettings.port));
    }

    client = new DefaultHttpClient(
            new SingleClientConnManager(httpParams/*file.httpClient.getParams()*/, schemeRegistry),
            httpParams/*file.httpClient.getParams()*/);

    if (proxySettings != null) {
        client.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(proxySettings.userName, proxySettings.password));
    }

    return client;
}

From source file:org.ebayopensource.fidouafclient.curl.Curl.java

private static HttpClient createHttpsClient() {
    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    SchemeRegistry registry = new SchemeRegistry();
    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
    registry.register(new Scheme("https", socketFactory, 443));
    HttpClient client = new DefaultHttpClient();
    SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
    DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());
    return httpClient;
}

From source file:com.dalaran.async.task.http.AbstractHTTPService.java

protected String callPostRemoteService(String url, String json) throws IOException {
    SchemeRegistry schReg = new SchemeRegistry();
    schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 2008));

    HttpPost httpPost = new HttpPost(url);

    StringEntity se = new StringEntity(json);
    se.setContentEncoding(HTTP.UTF_8);/*from   www.  j av  a2s. com*/
    //        httpPost.setHeader(HTTP.USER_AGENT, URLs.USER_AGENT);
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");
    SingleClientConnManager cm = new SingleClientConnManager(httpPost.getParams(), schReg);

    httpPost.setEntity(se);
    HttpClient client = new DefaultHttpClient();

    HttpResponse response = null;
    try {
        response = client.execute(httpPost);
        HttpEntity entity = response.getEntity();
        return responseToBuffer(client, entity);
    } catch (Exception e) {
        return null;
    }
}

From source file:org.apache.taverna.activities.rest.HTTPRequestHandler.java

/**
 * This method is the entry point to the invocation of a remote REST
 * service. It accepts a number of parameters from the related REST activity
 * and uses those to assemble, execute and fetch results of a relevant HTTP
 * request.//  w  w  w .  ja v a  2s  .co m
 *
 * @param requestURL
 *            The URL for the request to be made. This cannot be taken from
 *            the <code>configBean</code>, because this should be the
 *            complete URL which may be directly used to make the request (
 *            <code>configBean</code> would only contain the URL signature
 *            associated with the REST activity).
 * @param configBean
 *            Configuration of the associated REST activity is passed to
 *            this class as a configuration bean. Settings such as HTTP
 *            method, MIME types for "Content-Type" and "Accept" headers,
 *            etc are taken from the bean.
 * @param inputMessageBody
 *            Body of the message to be sent to the server - only needed for
 *            POST and PUT requests; for GET and DELETE it will be
 *            discarded.
 * @return
 */
@SuppressWarnings("deprecation")
public static HTTPRequestResponse initiateHTTPRequest(String requestURL,
        RESTActivityConfigurationBean configBean, Object inputMessageBody, Map<String, String> urlParameters,
        CredentialsProvider credentialsProvider) {
    ClientConnectionManager connectionManager = null;
    if (requestURL.toLowerCase().startsWith("https")) {
        // Register a protocol scheme for https that uses Taverna's
        // SSLSocketFactory
        try {
            URL url = new URL(requestURL); // the URL object which will
            // parse the port out for us
            int port = url.getPort();
            if (port == -1) // no port was defined in the URL
                port = HTTPS_DEFAULT_PORT; // default HTTPS port
            Scheme https = new Scheme("https",
                    new org.apache.http.conn.ssl.SSLSocketFactory(SSLContext.getDefault()), port);
            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(https);
            connectionManager = new SingleClientConnManager(null, schemeRegistry);
        } catch (MalformedURLException ex) {
            logger.error("Failed to extract port from the REST service URL: the URL " + requestURL
                    + " is malformed.", ex);
            // This will cause the REST activity to fail but this method
            // seems not to throw an exception so we'll just log the error
            // and let it go through
        } catch (NoSuchAlgorithmException ex2) {
            // This will cause the REST activity to fail but this method
            // seems not to throw an exception so we'll just log the error
            // and let it go through
            logger.error("Failed to create SSLContext for invoking the REST service over https.", ex2);
        }
    }

    switch (configBean.getHttpMethod()) {
    case GET:
        return doGET(connectionManager, requestURL, configBean, urlParameters, credentialsProvider);
    case POST:
        return doPOST(connectionManager, requestURL, configBean, inputMessageBody, urlParameters,
                credentialsProvider);
    case PUT:
        return doPUT(connectionManager, requestURL, configBean, inputMessageBody, urlParameters,
                credentialsProvider);
    case DELETE:
        return doDELETE(connectionManager, requestURL, configBean, urlParameters, credentialsProvider);
    default:
        return new HTTPRequestResponse(new Exception(
                "Error: something went wrong; " + "no failure has occurred, but but unexpected HTTP method (\""
                        + configBean.getHttpMethod() + "\") encountered."));
    }
}

From source file:Main.java

public static DefaultHttpClient setHttpPostProxyParams(int connTimeOut) {

    Log.d(TAG, "connTimeout -- called");

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

    HttpParams params = new BasicHttpParams();

    /*Log.d(TAG, "----Add Proxy---");
    HttpHost proxy = new HttpHost(Constants.PROXY_HOST.trim(),
      Constants.PROXY_PORT);/*  w ww.j  av  a  2s  . c om*/
    params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);*/

    params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
    params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
    params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

    //HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, connTimeOut);
    HttpConnectionParams.setSoTimeout(params, connTimeOut);

    ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);

    DefaultHttpClient mHttpClient = new DefaultHttpClient(cm, params);

    return mHttpClient;
}

From source file:com.villemos.ispace.httpcrawler.HttpAccessor.java

public int poll() throws Exception {

    /** Always ignore authentication protocol errors. */
    if (ignoreAuthenticationFailure) {
        SSLContext sslContext = SSLContext.getInstance("SSL");

        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new EasyX509TrustManager() }, new SecureRandom());

        SchemeRegistry schemeRegistry = new SchemeRegistry();

        SSLSocketFactory sf = new SSLSocketFactory(sslContext);
        Scheme httpsScheme = new Scheme("https", sf, 443);
        schemeRegistry.register(httpsScheme);

        SocketFactory sfa = new PlainSocketFactory();
        Scheme httpScheme = new Scheme("http", sfa, 80);
        schemeRegistry.register(httpScheme);

        HttpParams params = new BasicHttpParams();
        ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);

        client = new DefaultHttpClient(cm, params);
    } else {//from  w  w  w .  j  av a  2  s.co  m
        client = new DefaultHttpClient();
    }

    String proxyHost = getHttpCrawlerEndpoint().getProxyHost();
    Integer proxyPort = getHttpCrawlerEndpoint().getProxyPort();

    if (proxyHost != null && proxyPort != null) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    } else {
        ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
        client.setRoutePlanner(routePlanner);
    }

    /** The target location may demand authentication. We setup preemptive authentication. */
    if (getHttpCrawlerEndpoint().getAuthenticationUser() != null
            && getHttpCrawlerEndpoint().getAuthenticationPassword() != null) {
        client.getCredentialsProvider().setCredentials(
                new AuthScope(getHttpCrawlerEndpoint().getDomain(), getHttpCrawlerEndpoint().getPort()),
                new UsernamePasswordCredentials(getHttpCrawlerEndpoint().getAuthenticationUser(),
                        getHttpCrawlerEndpoint().getAuthenticationPassword()));
    }

    /** Set default cookie policy and store. Can be overridden for a specific method using for example;
     *    method.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); 
     */
    client.setCookieStore(cookieStore);
    client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

    String uriStr = getHttpCrawlerEndpoint().getProtocol() + "://" + getHttpCrawlerEndpoint().getDomain();
    if (getHttpCrawlerEndpoint().getPort() != 80) {
        uriStr += ":" + getHttpCrawlerEndpoint().getPort() + "" + getHttpCrawlerEndpoint().getPath();
    } else {
        uriStr += getHttpCrawlerEndpoint().getPath();
    }
    URI uri = new URI(uriStr);

    if (getHttpCrawlerEndpoint().getPort() != 80) {
        target = new HttpHost(getHttpCrawlerEndpoint().getDomain(), getHttpCrawlerEndpoint().getPort(),
                getHttpCrawlerEndpoint().getProtocol());
    } else {
        target = new HttpHost(getHttpCrawlerEndpoint().getDomain());
    }
    localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    /** Default boundary is the domain. */
    getHttpCrawlerEndpoint().getBoundaries()
            .add(getHttpCrawlerEndpoint().getProtocol() + "://" + getHttpCrawlerEndpoint().getDomain());

    HttpUriRequest method = createInitialRequest(uri);
    HttpResponse response = client.execute(target, method, localContext);

    if (response.getStatusLine().getStatusCode() == 200) {
        processSite(uri, response);
    } else if (response.getStatusLine().getStatusCode() == 302) {
        HttpHost target = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        HttpGet get = new HttpGet(target.toURI());
        // HttpGet get = new HttpGet("https://om.eo.esa.int/oem/kt/dashboard.php");

        /** Read the response fully, to clear it. */
        HttpEntity entity = response.getEntity();
        HttpClientConfigurer.readFully(entity.getContent());

        response = client.execute(target, get, localContext);
        processSite(uri, response);
        System.out.println("Final target: " + target);
    } else {
        HttpEntity entity = response.getEntity();
        InputStream instream = entity.getContent();
        System.out.println(HttpClientConfigurer.readFully(instream));
    }

    return 0;
}

From source file:info.semanticsoftware.semassist.android.intents.ServiceIntent.java

public String execute() {
    Log.d(Constants.TAG, "factory execute for " + pipelineName + " on server " + candidServerURL + " params "
            + RTParams + " input " + inputString);
    if (candidServerURL.indexOf("https") < 0) {
        Log.d(Constants.TAG, "non secure post to " + candidServerURL);
        RequestRepresentation request = new RequestRepresentation(SemAssistApp.getInstance(), pipelineName,
                RTParams, inputString);/*from w ww  . ja v a 2  s  .co m*/
        Representation representation = new StringRepresentation(request.getXML(), MediaType.APPLICATION_XML);
        Representation response = new ClientResource(candidServerURL).post(representation);
        String responseString = "";
        try {
            StringWriter writer = new StringWriter();
            response.write(writer);
            responseString = writer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.d(Constants.TAG, "$$$ " + responseString);
        return responseString;
    } else {
        try {
            HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
            DefaultHttpClient client = new DefaultHttpClient();

            SchemeRegistry registry = new SchemeRegistry();
            final KeyStore ks = KeyStore.getInstance("BKS");
            // NOTE: the keystore must have been generated with BKS 146 and not later
            final InputStream in = SemAssistApp.getInstance().getContext().getResources()
                    .openRawResource(R.raw.clientkeystorenew);
            try {
                ks.load(in, SemAssistApp.getInstance().getContext().getString(R.string.keystorePassword)
                        .toCharArray());
            } finally {
                in.close();
            }

            SSLSocketFactory socketFactory = new CustomSSLSocketFactory(ks);
            socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
            registry.register(new Scheme("https", socketFactory, 443));
            SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
            DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());

            // Set verifier
            HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
            RequestRepresentation request = new RequestRepresentation(SemAssistApp.getInstance(), pipelineName,
                    RTParams, inputString);
            Representation representation = new StringRepresentation(request.getXML(),
                    MediaType.APPLICATION_XML);

            HttpPost post = new HttpPost(candidServerURL);
            post.setEntity(new StringEntity(representation.getText()));

            HttpResponse response = httpClient.execute(post);
            HttpEntity entity = response.getEntity();
            InputStream inputstream = entity.getContent();
            InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
            BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

            String string = null;
            String responseString = "";
            while ((string = bufferedreader.readLine()) != null) {
                responseString += string;
            }
            return responseString;
        } catch (Exception e) {
            e.printStackTrace();
        }
    } //else
    return null;
}