Example usage for org.apache.http.auth AuthScope ANY_PORT

List of usage examples for org.apache.http.auth AuthScope ANY_PORT

Introduction

In this page you can find the example usage for org.apache.http.auth AuthScope ANY_PORT.

Prototype

int ANY_PORT

To view the source code for org.apache.http.auth AuthScope ANY_PORT.

Click Source Link

Document

The -1 value represents any port.

Usage

From source file:uk.org.openeyes.oink.itest.adapters.ITProxyAdapter.java

@Test
public void testPractitionerCreateUpdateAndDelete() throws Exception {

    // CREATE//from   ww  w  . j  av a2 s .  c  om
    OINKRequestMessage req = new OINKRequestMessage();
    req.setResourcePath("/Practitioner");
    req.setMethod(HttpMethod.POST);
    req.addProfile("http://openeyes.org.uk/fhir/1.7.0/profile/Practitioner/Gp");
    InputStream is = ITProxyAdapter.class.getResourceAsStream("/example-messages/fhir/practitioner2.json");
    Parser parser = new JsonParser();
    Practitioner p = (Practitioner) parser.parse(is);
    FhirBody body = new FhirBody(p);
    req.setBody(body);

    RabbitClient client = new RabbitClient(props.getProperty("rabbit.host"),
            Integer.parseInt(props.getProperty("rabbit.port")), props.getProperty("rabbit.vhost"),
            props.getProperty("rabbit.username"), props.getProperty("rabbit.password"));

    OINKResponseMessage resp = client.sendAndRecieve(req, props.getProperty("rabbit.routingKey"),
            props.getProperty("rabbit.defaultExchange"));

    assertEquals(201, resp.getStatus());
    String locationHeader = resp.getLocationHeader();
    assertNotNull(locationHeader);
    assertFalse(locationHeader.isEmpty());
    log.info("Posted to " + locationHeader);

    // See if Patient exists
    DefaultHttpClient httpClient = new DefaultHttpClient();

    httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials("admin", "admin"));

    HttpGet httpGet = new HttpGet(locationHeader);
    httpGet.setHeader("Accept", "application/fhir+json");
    HttpResponse response1 = httpClient.execute(httpGet);
    assertEquals(200, response1.getStatusLine().getStatusCode());

    // UPDATE
    String id = getIdFromLocationHeader("Practitioner", locationHeader);
    OINKRequestMessage updateRequest = new OINKRequestMessage();
    updateRequest.setResourcePath("/Practitioner/" + id);
    updateRequest.setMethod(HttpMethod.PUT);
    updateRequest.addProfile("http://openeyes.org.uk/fhir/1.7.0/profile/Practitioner/Gp");
    p.getTelecom().get(0).setValueSimple("0222 222 2222");
    updateRequest.setBody(new FhirBody(p));

    OINKResponseMessage updateResponse = client.sendAndRecieve(updateRequest,
            props.getProperty("rabbit.routingKey"), props.getProperty("rabbit.defaultExchange"));
    assertEquals(200, updateResponse.getStatus());

    // DELETE
    OINKRequestMessage deleteRequest = new OINKRequestMessage();
    deleteRequest.setResourcePath("/Practitioner/" + id);
    deleteRequest.setMethod(HttpMethod.DELETE);
    deleteRequest.addProfile("http://openeyes.org.uk/fhir/1.7.0/profile/Practitioner/Gp");

    OINKResponseMessage deleteResponse = client.sendAndRecieve(deleteRequest,
            props.getProperty("rabbit.routingKey"), props.getProperty("rabbit.defaultExchange"));
    assertEquals(204, deleteResponse.getStatus());

}

From source file:com.hp.saas.agm.rest.client.AliRestClient.java

@Override
public synchronized void login() {
    // exclude the NTLM authentication scheme (requires NTCredentials we don't supply)
    List<String> authPrefs = new ArrayList<String>(2);
    authPrefs.add(AuthPolicy.DIGEST);/* w  w  w.j av a2s. com*/
    authPrefs.add(AuthPolicy.BASIC);
    httpClient.getParams().setParameter("http.auth.scheme-priority", authPrefs);

    // first try Apollo style login
    String authPoint = pathJoin("/", location, "/authentication-point/alm-authenticate");
    String authXml = createAuthXml();
    HttpPost post = initHttpPost(authPoint, authXml);
    ResultInfo resultInfo = ResultInfo.create(null);
    executeAndWriteResponse(post, resultInfo, Collections.<Integer>emptySet());

    if (resultInfo.getHttpStatus() == HttpStatus.SC_NOT_FOUND) {
        // try Maya style login
        Credentials cred = new UsernamePasswordCredentials(userName, password);
        AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
        httpClient.getParams().setParameter("http.protocol.credential-charset", "UTF-8");
        //todo?
        httpClient.getCredentialsProvider().setCredentials(scope, cred);

        authPoint = pathJoin("/", location, "/authentication-point/authenticate");
        HttpGet get = new HttpGet(authPoint);
        resultInfo = ResultInfo.create(null);
        executeAndWriteResponse(get, resultInfo, Collections.<Integer>emptySet());
    }
    HttpStatusBasedException.throwForError(resultInfo);
    if (resultInfo.getHttpStatus() != 200) {
        // during login we only accept 200 status (to avoid redirects and such as seemingly correct login)
        throw new AuthenticationFailureException(resultInfo);
    }

    List<Cookie> cookies = httpClient.getCookieStore().getCookies();
    Cookie ssoCookie = getSessionCookieByName(cookies, COOKIE_SSO_NAME);
    addTenantCookie(ssoCookie);

    //Since ALM 12.00 it is required explicitly ask for QCSession calling "/rest/site-session"
    //For all the rest of HP ALM / AGM versions it is optional
    String siteSessionPoint = pathJoin("/", location, "/rest/site-session");
    String sessionParamXml = createRestSessionXml();
    post = initHttpPost(siteSessionPoint, sessionParamXml);
    resultInfo = ResultInfo.create(null);
    executeAndWriteResponse(post, resultInfo, Collections.<Integer>emptySet());
    //AGM throws 403
    if (resultInfo.getHttpStatus() != HttpStatus.SC_FORBIDDEN) {
        HttpStatusBasedException.throwForError(resultInfo);
    }

    cookies = httpClient.getCookieStore().getCookies();
    BasicClientCookie qcCookie = (BasicClientCookie) getSessionCookieByName(cookies, COOKIE_SESSION_NAME);
    sessionContext = new SessionContext(location, ssoCookie, qcCookie);
}

From source file:org.modelio.vbasic.net.ApacheUriConnection.java

/**
 * Configure proxy authentication from the given properties.
 * @see <a href="http://stackoverflow.com/questions/1626549/authenticated-http-proxy-with-java">stackoverflow: Authenticated HTTP proxy with Java</a>
 * @see org.eclipse.core.internal.net.ProxyType
 * @param props configuration source//from   w w w .  j a v  a  2 s. c o  m
 * @param protocol = http/https
 * @param credsProvider the credential provider to fill
 */
@objid("fbda3db8-0195-4690-81dc-81ecfe95a586")
@SuppressWarnings("javadoc")
private void configProxyCredentials(Properties props, String protocol, CredentialsProvider credsProvider) {
    /*
     * http://docs.oracle.com/javase/7/docs/api/java/net/doc-files/net-properties.html:
     * 
      There are 3 properties you can set to specify the proxy that will be used by the http protocol handler:
    http.proxyHost: the host name of the proxy server
    http.proxyPort: the port number, the default value being 80.
            
      proxyUser and proxyPassword are not used by the JDK but are set by Eclipse preference page.
      see : org.eclipse.core.internal.net.ProxyType
     */

    String proxyHostKey = protocol + ".proxyHost";
    String proxyUserKey = protocol + ".proxyUser";

    if (props.containsKey(proxyHostKey) && props.containsKey(proxyUserKey)) {

        String proxyPortKey = protocol + ".proxyPort";
        String proxyPasswdKey = protocol + ".proxyPassword";

        String user = props.getProperty(proxyUserKey);
        String pwd = props.getProperty(proxyPasswdKey);
        String sport = props.getProperty(proxyPortKey);

        int port = sport != null ? Integer.parseInt(sport) : AuthScope.ANY_PORT;

        final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, pwd);

        final AuthScope authscope = new AuthScope(this.uri.getHost(), port);
        credsProvider.setCredentials(authscope, credentials);

    }
}

From source file:com.mirth.connect.connectors.http.HttpDispatcher.java

@Override
public Response send(ConnectorProperties connectorProperties, ConnectorMessage connectorMessage) {
    HttpDispatcherProperties httpDispatcherProperties = (HttpDispatcherProperties) connectorProperties;
    eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
            getDestinationName(), ConnectionStatusEventType.WRITING));

    String responseData = null;/*from  w  w  w.  j ava 2 s . c om*/
    String responseError = null;
    String responseStatusMessage = null;
    Status responseStatus = Status.QUEUED;
    boolean validateResponse = false;

    CloseableHttpClient client = null;
    HttpRequestBase httpMethod = null;
    CloseableHttpResponse httpResponse = null;
    File tempFile = null;
    int socketTimeout = NumberUtils.toInt(httpDispatcherProperties.getSocketTimeout(), 30000);

    try {
        configuration.configureDispatcher(this, httpDispatcherProperties);

        long dispatcherId = getDispatcherId();
        client = clients.get(dispatcherId);
        if (client == null) {
            BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager(
                    socketFactoryRegistry.build());
            httpClientConnectionManager
                    .setSocketConfig(SocketConfig.custom().setSoTimeout(socketTimeout).build());
            HttpClientBuilder clientBuilder = HttpClients.custom()
                    .setConnectionManager(httpClientConnectionManager);
            HttpUtil.configureClientBuilder(clientBuilder);

            if (httpDispatcherProperties.isUseProxyServer()) {
                clientBuilder.setRoutePlanner(new DynamicProxyRoutePlanner());
            }

            client = clientBuilder.build();
            clients.put(dispatcherId, client);
        }

        URI hostURI = new URI(httpDispatcherProperties.getHost());
        String host = hostURI.getHost();
        String scheme = hostURI.getScheme();
        int port = hostURI.getPort();
        if (port == -1) {
            if (scheme.equalsIgnoreCase("https")) {
                port = 443;
            } else {
                port = 80;
            }
        }

        // Parse the content type field first, and then add the charset if needed
        ContentType contentType = ContentType.parse(httpDispatcherProperties.getContentType());
        Charset charset = null;
        if (contentType.getCharset() == null) {
            charset = Charset.forName(CharsetUtils.getEncoding(httpDispatcherProperties.getCharset()));
        } else {
            charset = contentType.getCharset();
        }

        if (httpDispatcherProperties.isMultipart()) {
            tempFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
        }

        HttpHost target = new HttpHost(host, port, scheme);

        httpMethod = buildHttpRequest(hostURI, httpDispatcherProperties, connectorMessage, tempFile,
                contentType, charset);

        HttpClientContext context = HttpClientContext.create();

        // authentication
        if (httpDispatcherProperties.isUseAuthentication()) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
            Credentials credentials = new UsernamePasswordCredentials(httpDispatcherProperties.getUsername(),
                    httpDispatcherProperties.getPassword());
            credsProvider.setCredentials(authScope, credentials);
            AuthCache authCache = new BasicAuthCache();
            RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder.<AuthSchemeProvider>create();

            if (AuthSchemes.DIGEST.equalsIgnoreCase(httpDispatcherProperties.getAuthenticationType())) {
                logger.debug("using Digest authentication");
                registryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory(charset));

                if (httpDispatcherProperties.isUsePreemptiveAuthentication()) {
                    processDigestChallenge(authCache, target, credentials, httpMethod, context);
                }
            } else {
                logger.debug("using Basic authentication");
                registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory(charset));

                if (httpDispatcherProperties.isUsePreemptiveAuthentication()) {
                    authCache.put(target, new BasicScheme());
                }
            }

            context.setCredentialsProvider(credsProvider);
            context.setAuthSchemeRegistry(registryBuilder.build());
            context.setAuthCache(authCache);

            logger.debug("using authentication with credentials: " + credentials);
        }

        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(socketTimeout)
                .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true).build();
        context.setRequestConfig(requestConfig);

        // Set proxy information
        if (httpDispatcherProperties.isUseProxyServer()) {
            context.setAttribute(PROXY_CONTEXT_KEY, new HttpHost(httpDispatcherProperties.getProxyAddress(),
                    Integer.parseInt(httpDispatcherProperties.getProxyPort())));
        }

        // execute the method
        logger.debug(
                "executing method: type=" + httpMethod.getMethod() + ", uri=" + httpMethod.getURI().toString());
        httpResponse = client.execute(target, httpMethod, context);
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        logger.debug("received status code: " + statusCode);

        Map<String, List<String>> headers = new HashMap<String, List<String>>();
        for (Header header : httpResponse.getAllHeaders()) {
            List<String> list = headers.get(header.getName());

            if (list == null) {
                list = new ArrayList<String>();
                headers.put(header.getName(), list);
            }

            list.add(header.getValue());
        }

        connectorMessage.getConnectorMap().put("responseStatusLine", statusLine.toString());
        connectorMessage.getConnectorMap().put("responseHeaders",
                new MessageHeaders(new CaseInsensitiveMap(headers)));

        ContentType responseContentType = ContentType.get(httpResponse.getEntity());
        if (responseContentType == null) {
            responseContentType = ContentType.TEXT_PLAIN;
        }

        Charset responseCharset = charset;
        if (responseContentType.getCharset() != null) {
            responseCharset = responseContentType.getCharset();
        }

        final String responseBinaryMimeTypes = httpDispatcherProperties.getResponseBinaryMimeTypes();
        BinaryContentTypeResolver binaryContentTypeResolver = new BinaryContentTypeResolver() {
            @Override
            public boolean isBinaryContentType(ContentType contentType) {
                return HttpDispatcher.this.isBinaryContentType(responseBinaryMimeTypes, contentType);
            }
        };

        /*
         * First parse out the body of the HTTP response. Depending on the connector settings,
         * this could end up being a string encoded with the response charset, a byte array
         * representing the raw response payload, or a MimeMultipart object.
         */
        Object responseBody = "";

        // The entity could be null in certain cases such as 204 responses
        if (httpResponse.getEntity() != null) {
            // Only parse multipart if XML Body is selected and Parse Multipart is enabled
            if (httpDispatcherProperties.isResponseXmlBody()
                    && httpDispatcherProperties.isResponseParseMultipart()
                    && responseContentType.getMimeType().startsWith(FileUploadBase.MULTIPART)) {
                responseBody = new MimeMultipart(new ByteArrayDataSource(httpResponse.getEntity().getContent(),
                        responseContentType.toString()));
            } else if (binaryContentTypeResolver.isBinaryContentType(responseContentType)) {
                responseBody = IOUtils.toByteArray(httpResponse.getEntity().getContent());
            } else {
                responseBody = IOUtils.toString(httpResponse.getEntity().getContent(), responseCharset);
            }
        }

        /*
         * Now that we have the response body, we need to create the actual Response message
         * data. Depending on the connector settings this could be our custom serialized XML, a
         * Base64 string encoded from the raw response payload, or a string encoded from the
         * payload with the request charset.
         */
        if (httpDispatcherProperties.isResponseXmlBody()) {
            responseData = HttpMessageConverter.httpResponseToXml(statusLine.toString(), headers, responseBody,
                    responseContentType, httpDispatcherProperties.isResponseParseMultipart(),
                    httpDispatcherProperties.isResponseIncludeMetadata(), binaryContentTypeResolver);
        } else if (responseBody instanceof byte[]) {
            responseData = new String(Base64Util.encodeBase64((byte[]) responseBody), "US-ASCII");
        } else {
            responseData = (String) responseBody;
        }

        validateResponse = httpDispatcherProperties.getDestinationConnectorProperties().isValidateResponse();

        if (statusCode < HttpStatus.SC_BAD_REQUEST) {
            responseStatus = Status.SENT;
        } else {
            eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                    connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                    connectorProperties.getName(), "Received error response from HTTP server.", null));
            responseStatusMessage = ErrorMessageBuilder
                    .buildErrorResponse("Received error response from HTTP server.", null);
            responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(), responseData,
                    null);
        }
    } catch (Exception e) {
        eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                connectorProperties.getName(), "Error connecting to HTTP server.", e));
        responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("Error connecting to HTTP server", e);
        responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(),
                "Error connecting to HTTP server", e);
    } finally {
        try {
            HttpClientUtils.closeQuietly(httpResponse);

            // Delete temp files if we created them
            if (tempFile != null) {
                tempFile.delete();
                tempFile = null;
            }
        } finally {
            eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                    getDestinationName(), ConnectionStatusEventType.IDLE));
        }
    }

    return new Response(responseStatus, responseData, responseStatusMessage, responseError, validateResponse);
}

From source file:com.olacabs.fabric.processors.httpwriter.HttpWriter.java

private void setAuth(AuthConfiguration authConfiguration, HttpClientBuilder builder)
        throws InitializationException {
    if (!Strings.isNullOrEmpty(authConfiguration.getUsername())) {
        Credentials credentials = new UsernamePasswordCredentials(authConfiguration.getUsername(),
                authConfiguration.getPassword());
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), credentials);

        builder.addInterceptorFirst((HttpRequestInterceptor) (request, context) -> {
            AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);
            if (authState.getAuthScheme() == null) {
                //log.debug("SETTING CREDS");
                //log.info("Preemptive AuthState: {}", authState);
                authState.update(new BasicScheme(), credentials);
            }//from  ww  w.  j  av a 2 s  . c  o m
        });

    } else {
        log.error("Username can't be blank for basic auth.");
        throw new InitializationException("Username blank for basic auth");
    }
}

From source file:eu.diacron.crawlservice.app.Util.java

public static void getAllCrawls() {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(Configuration.REMOTE_CRAWLER_USERNAME,
                    Configuration.REMOTE_CRAWLER_PASS));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try {/*from www.  j a v a  2  s. com*/
        //HttpGet httpget = new HttpGet("http://diachron.hanzoarchives.com/crawl");
        HttpGet httpget = new HttpGet(Configuration.REMOTE_CRAWLER_URL_CRAWL);

        System.out.println("Executing request " + httpget.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.println("----------------------------------------");

            System.out.println(response.getEntity().getContent());

            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
            }
            in.close();
            EntityUtils.consume(response.getEntity());
        } finally {
            response.close();
        }
    } catch (IOException ex) {
        Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            httpclient.close();
        } catch (IOException ex) {
            Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:org.hyperic.plugin.vrealize.automation.DiscoveryVRAIaasWeb.java

private static String getVCO(ConfigResponse config) {
    String vcoFNQ = null;/*from   ww w . j  a va 2  s . co m*/
    String xml = null;

    String user = config.getValue("iaas.http.user", "");
    String pass = config.getValue("iaas.http.pass", "");
    String domain = config.getValue("iaas.http.domain", "");

    try {
        AgentKeystoreConfig ksCFG = new AgentKeystoreConfig();
        HQHttpClient client = new HQHttpClient(ksCFG, new HttpConfig(5000, 5000, null, 0),
                ksCFG.isAcceptUnverifiedCert());

        List<String> authpref = new ArrayList<String>();
        authpref.add(AuthPolicy.NTLM);
        authpref.add(AuthPolicy.BASIC);
        client.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);

        client.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthPolicy.NTLM),
                new NTCredentials(user, pass, "localhost", domain));

        HttpGet get = new HttpGet(
                "https://localhost/Repository/Data/ManagementModelEntities.svc/ManagementEndpoints");
        HttpResponse response = client.execute(get);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 200) {
            xml = readInputString(response.getEntity().getContent());
        } else {
            log.debug("[getVCOx] GET failed: " + response.getStatusLine().getReasonPhrase());
        }
    } catch (IOException ex) {
        log.debug("[getVCOx] " + ex, ex);
    }

    if (xml != null) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = (Document) builder.parse(new ByteArrayInputStream(xml.getBytes()));

            log.debug("[getVCOx] xml:" + xml);

            XPathFactory xFactory = XPathFactory.newInstance();
            XPath xpath = xFactory.newXPath();

            String xPath = "//properties[InterfaceType[text()='vCO']]/ManagementEndpointName/text()";

            log.debug("[getVCOx] evaluating XPath:" + xPath);

            vcoFNQ = xpath.evaluate(xPath, doc);

            log.debug("[getVCOx] vcoFNQ:" + vcoFNQ);

        } catch (Exception ex) {
            log.debug("[getVCOx] " + ex, ex);
        }
    }

    return VRAUtils.getFqdn(vcoFNQ);
}

From source file:com.ibm.dataworks.DataLoadResource.java

/** 
 * Create an HTTP client object that is authenticated with the user and password
 * of the IBM DataWorks Service.//from   w ww.j  a va2 s  .  co m
 */
private HttpClient getAuthenticatedHttpClient() throws GeneralSecurityException {
    // NOTE: If you re-purpose this code for your own application you might want to have 
    // additional security mechanisms in place regarding certificate authentication.

    // build credentials object
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(vcapInfo.getUser(),
            vcapInfo.getPassword());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), creds);
    // For demo purposes only: always accept the certificate 
    TrustStrategy accepAllTrustStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] certificate, String authType) {
            return true;
        }
    };
    SSLContextBuilder contextBuilder = new SSLContextBuilder();
    SSLContext context = contextBuilder.loadTrustMaterial(null, accepAllTrustStrategy).build();
    SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(context, new AllowAllHostnameVerifier());

    HttpClient httpClient = HttpClientBuilder.create() //
            .setSSLSocketFactory(scsf) //
            .setDefaultCredentialsProvider(credsProvider) //
            .build();

    return httpClient;
}

From source file:com.gs.tools.doc.extractor.core.util.HttpUtility.java

public static DefaultHttpClient getLoginHttpsClient(String userName, String password) {
    try {/*from   w  w  w.j av  a  2 s. c  om*/
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new DefaultSecureSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        HttpConnectionParams.setConnectionTimeout(params, 300000);
        HttpConnectionParams.setSocketBufferSize(params, 10485760);
        HttpConnectionParams.setSoTimeout(params, 300000);

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

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        DefaultHttpClient httpClient = new DefaultHttpClient(ccm, params);
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
                new UsernamePasswordCredentials(userName, password));
        return httpClient;
    } catch (Exception e) {
        e.printStackTrace();
        return new DefaultHttpClient();
    }
}