Example usage for org.apache.http.client.config CookieSpecs STANDARD

List of usage examples for org.apache.http.client.config CookieSpecs STANDARD

Introduction

In this page you can find the example usage for org.apache.http.client.config CookieSpecs STANDARD.

Prototype

String STANDARD

To view the source code for org.apache.http.client.config CookieSpecs STANDARD.

Click Source Link

Document

The RFC 2965 compliant policy (standard).

Usage

From source file:interoperabilite.webservice.client.ClientCustomPublicSuffixList.java

public final static void main(String[] args) throws Exception {

    // Use PublicSuffixMatcherLoader to load public suffix list from a file,
    // resource or from an arbitrary URL
    PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader
            .load(new URL("https://publicsuffix.org/list/effective_tld_names.dat"));

    // Please use the publicsuffix.org URL to download the list no more than once per day !!!
    // Please consider making a local copy !!!

    DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);

    RFC6265CookieSpecProvider cookieSpecProvider = new RFC6265CookieSpecProvider(publicSuffixMatcher);
    Lookup<CookieSpecProvider> cookieSpecRegistry = RegistryBuilder.<CookieSpecProvider>create()
            .register(CookieSpecs.DEFAULT, cookieSpecProvider)
            .register(CookieSpecs.STANDARD, cookieSpecProvider)
            .register(CookieSpecs.STANDARD_STRICT, cookieSpecProvider).build();

    CloseableHttpClient httpclient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier)
            .setDefaultCookieSpecRegistry(cookieSpecRegistry).build();
    try {//  w  w  w.  ja v a 2s.  co m

        HttpGet httpget = new HttpGet("https://httpbin.org/");

        System.out.println("executing request " + httpget.getRequestLine());

        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:it.av.wikipedia.client.WikipediaClient.java

public static String Query(QueryParameters params) {
    try (CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build())
            .build()) {//from w w  w  . java 2 s . c om
        StringBuilder url = new StringBuilder(ENDPOINT);
        url.append(params.toURLQueryString());

        //System.out.println("GET: " + url);
        HttpGet request = new HttpGet(url.toString());
        request.setHeader("User-Agent", "FACWikiTool");

        // Create a custom response handler
        ResponseHandler<String> responseHandler = (final HttpResponse response) -> {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
        };

        return httpclient.execute(request, responseHandler);
    } catch (IOException ex) {
        Logger.getLogger(WikipediaClient.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:com.afrisoftech.lib.PDF2ExcelConverter.java

public static void convertPDf2Excel(String pdfFile2Convert) throws Exception {
    if (pdfFile2Convert.length() < 3) {
        System.out.println("File to convert is mandatory!");
        javax.swing.JOptionPane.showMessageDialog(null, "File to convert is mandatory!");
    } else {//  ww  w .j a  v  a  2 s . c om

        final String apiKey = "ktxpfvf0i5se";
        final String format = "xlsx-single".toLowerCase();
        final String pdfFilename = pdfFile2Convert;

        if (!formats.contains(format)) {
            System.out.println("Invalid output format: \"" + format + "\"");
        }

        // Avoid cookie warning with default cookie configuration
        RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();

        File inputFile = new File(pdfFilename);

        if (!inputFile.canRead()) {
            System.out.println("Can't read input PDF file: \"" + pdfFilename + "\"");
            javax.swing.JOptionPane.showMessageDialog(null, "File to convert is mandatory!");
        }

        try (CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                .build()) {
            HttpPost httppost = new HttpPost("https://pdftables.com/api?format=" + format + "&key=" + apiKey);
            FileBody fileBody = new FileBody(inputFile);

            HttpEntity requestBody = MultipartEntityBuilder.create().addPart("f", fileBody).build();
            httppost.setEntity(requestBody);

            System.out.println("Sending request");

            try (CloseableHttpResponse response = httpclient.execute(httppost)) {
                if (response.getStatusLine().getStatusCode() != 200) {
                    System.out.println(response.getStatusLine());
                    javax.swing.JOptionPane.showMessageDialog(null,
                            "Internet connection is a must. Consult IT administrator for further assistance");
                }
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    final String outputFilename = getOutputFilename(pdfFilename,
                            format.replaceFirst("-.*$", ""));
                    System.out.println("Writing output to " + outputFilename);

                    final File outputFile = new File(outputFilename);
                    FileUtils.copyInputStreamToFile(resEntity.getContent(), outputFile);
                    if (java.awt.Desktop.isDesktopSupported()) {
                        try {
                            java.awt.Desktop.getDesktop().open(outputFile);
                        } catch (IOException ex) {
                            javax.swing.JOptionPane.showMessageDialog(new java.awt.Frame(), ex.getMessage());
                            ex.printStackTrace(); //Exceptions.printStackTrace(ex);
                        }
                    }
                } else {
                    System.out.println("Error: file missing from response");
                    javax.swing.JOptionPane.showMessageDialog(null,
                            "Error: file missing from response! Internet connection is a must.");
                }
            }
        }
    }
}

From source file:org.mobicents.servlet.restcomm.http.CustomHttpClientBuilder.java

public static HttpClient build(MainConfigurationSet config) {
    SslMode mode = config.getSslMode();// w ww  .  ja v a2s .c o m
    int timeoutConnection = config.getResponseTimeout();
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutConnection)
            .setConnectionRequestTimeout(timeoutConnection).setSocketTimeout(timeoutConnection)
            .setCookieSpec(CookieSpecs.STANDARD).build();
    if (mode == SslMode.strict) {
        return HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
    } else {
        return buildAllowallClient(requestConfig);
    }
}

From source file:org.restcomm.connect.commons.common.http.CustomHttpClientBuilder.java

public static HttpClient build(MainConfigurationSet config, int timeout) {
    SslMode mode = config.getSslMode();//  w  w w.j a  v a 2s  .  c o  m
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout)
            .setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).setCookieSpec(CookieSpecs.STANDARD)
            .build();
    if (mode == SslMode.strict) {
        return HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
    } else {
        return buildAllowallClient(requestConfig);
    }
}

From source file:org.ligoj.app.http.security.RestAuthenticationProvider.java

@Override
public Authentication authenticate(final Authentication authentication) {
    final String userpassword = StringUtils.defaultString(authentication.getCredentials().toString(), "");
    final String userName = StringUtils.lowerCase(authentication.getPrincipal().toString());

    // First get the cookie
    final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build());
    final HttpPost httpPost = new HttpPost(getSsoPostUrl());

    // Do the POST
    try (CloseableHttpClient httpClient = clientBuilder.build()) {
        final String content = String.format(getSsoPostContent(), userName, userpassword);
        httpPost.setEntity(new StringEntity(content, StandardCharsets.UTF_8));
        httpPost.setHeader("Content-Type", "application/json");
        final HttpResponse httpResponse = httpClient.execute(httpPost);
        if (HttpStatus.SC_NO_CONTENT == httpResponse.getStatusLine().getStatusCode()) {
            // Succeed authentication, save the cookies data inside the authentication
            return newAuthentication(userName, userpassword, authentication, httpResponse);
        }/* www.ja va  2 s .  com*/
        log.info("Failed authentication of {}[{}] : {}", userName, userpassword.length(),
                httpResponse.getStatusLine().getStatusCode());
        httpResponse.getEntity().getContent().close();
    } catch (final IOException e) {
        log.warn("Remote SSO server is not available", e);
    }
    throw new BadCredentialsException("Invalid user or password");
}

From source file:com.mirth.connect.util.HttpUtil.java

/**
 * Applies global settings to any Apache HttpComponents HttpClientBuilder.<br/>
 * <br/>/*from  w w w . j  a va2  s  . c  o  m*/
 * As of version 4.5, the default cookie specifications used by Apache HttpClient are more
 * strict in order to abide by RFC 6265. As part of this change, domain parameters in cookies
 * are checked against a public ICANN suffix matcher before they are allowed to be added to
 * outgoing requests. However this may cause clients to fail to connect if they are using custom
 * hostnames like "mycustomhost". To prevent that, we're building our own CookieSpecProvider
 * registry, and setting that on the client. Look at CookieSpecRegistries to see how the default
 * registry is built. The only difference now is that DefaultCookieSpecProvider is being
 * constructed without a PublicSuffixMatcher.
 */
public static void configureClientBuilder(HttpClientBuilder clientBuilder) {
    PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.getDefault();
    clientBuilder.setPublicSuffixMatcher(publicSuffixMatcher);
    RegistryBuilder<CookieSpecProvider> cookieSpecBuilder = RegistryBuilder.<CookieSpecProvider>create();
    CookieSpecProvider defaultProvider = new DefaultCookieSpecProvider();
    CookieSpecProvider laxStandardProvider = new RFC6265CookieSpecProvider(
            RFC6265CookieSpecProvider.CompatibilityLevel.RELAXED, publicSuffixMatcher);
    CookieSpecProvider strictStandardProvider = new RFC6265CookieSpecProvider(
            RFC6265CookieSpecProvider.CompatibilityLevel.STRICT, publicSuffixMatcher);
    cookieSpecBuilder.register(CookieSpecs.DEFAULT, defaultProvider);
    cookieSpecBuilder.register("best-match", defaultProvider);
    cookieSpecBuilder.register("compatibility", defaultProvider);
    cookieSpecBuilder.register(CookieSpecs.STANDARD, laxStandardProvider);
    cookieSpecBuilder.register(CookieSpecs.STANDARD_STRICT, strictStandardProvider);
    cookieSpecBuilder.register(CookieSpecs.NETSCAPE, new NetscapeDraftSpecProvider());
    cookieSpecBuilder.register(CookieSpecs.IGNORE_COOKIES, new IgnoreSpecProvider());
    clientBuilder.setDefaultCookieSpecRegistry(cookieSpecBuilder.build());
}

From source file:org.wisdom.test.http.Options.java

/**
 * Refreshes the options, and restores defaults.
 *//*from  w  ww .j  a va2  s  . c o m*/
public static void refresh() {
    // Load timeouts
    Object connectionTimeout = Options.getOption(Option.CONNECTION_TIMEOUT);
    if (connectionTimeout == null) {
        connectionTimeout = CONNECTION_TIMEOUT;
    }

    Object socketTimeout = Options.getOption(Option.SOCKET_TIMEOUT);
    if (socketTimeout == null) {
        socketTimeout = SOCKET_TIMEOUT;
    }

    // Create common default configuration
    final BasicCookieStore store = new BasicCookieStore();
    RequestConfig clientConfig = RequestConfig.custom()
            .setConnectTimeout(((Long) connectionTimeout).intValue() * TimeUtils.TIME_FACTOR)
            .setSocketTimeout(((Long) socketTimeout).intValue() * TimeUtils.TIME_FACTOR)
            .setConnectionRequestTimeout(((Long) socketTimeout).intValue() * TimeUtils.TIME_FACTOR)
            .setCookieSpec(CookieSpecs.STANDARD).build();

    // Create clients
    setOption(Option.HTTPCLIENT, HttpClientBuilder.create().setDefaultRequestConfig(clientConfig)
            .setDefaultCookieStore(store).build());

    setOption(Option.COOKIES, store);

    CloseableHttpAsyncClient asyncClient = HttpAsyncClientBuilder.create().setDefaultRequestConfig(clientConfig)
            .setDefaultCookieStore(store).build();
    setOption(Option.ASYNCHTTPCLIENT, asyncClient);
}

From source file:com.tremolosecurity.unison.proxy.auth.openidconnect.loadUser.LoadAttributesFromWS.java

public Map loadUserAttributesFromIdP(HttpServletRequest request, HttpServletResponse response,
        ConfigManager cfg, HashMap<String, Attribute> authParams, Map accessToken) throws Exception {
    String bearerTokenName = authParams.get("bearerTokenName").getValues().get(0);
    String url = authParams.get("restURL").getValues().get(0);

    BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(
            GlobalEntries.getGlobalEntries().getConfigManager().getHttpClientSocketRegistry());
    RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
    CloseableHttpClient http = HttpClients.custom().setConnectionManager(bhcm).setDefaultRequestConfig(rc)
            .build();//from ww  w .  j  av  a  2s  . c  o m

    HttpGet get = new HttpGet(url);

    get.addHeader("Authorization", "Bearer " + request.getSession().getAttribute(bearerTokenName));

    CloseableHttpResponse httpResp = http.execute(get);

    BufferedReader in = new BufferedReader(new InputStreamReader(httpResp.getEntity().getContent()));

    StringBuffer token = new StringBuffer();

    String line = null;
    while ((line = in.readLine()) != null) {
        token.append(line);
    }

    httpResp.close();
    bhcm.close();

    Map jwtNVP = com.cedarsoftware.util.io.JsonReader.jsonToMaps(token.toString());

    return jwtNVP;

}

From source file:org.apache.trafficcontrol.client.RestApiSession.java

public void open() {
    if (httpclient == null) {
        RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD) //User standard instead of default. Default will result in cookie parse exceptions with the Mojolicous cookie
                .setConnectTimeout(5000).build();
        CookieStore cookieStore = new BasicCookieStore();
        HttpClientContext context = HttpClientContext.create();
        context.setCookieStore(cookieStore);

        httpclient = HttpAsyncClients.custom().setDefaultRequestConfig(globalConfig)
                .setDefaultCookieStore(cookieStore).build();
    }//from   w ww .j a va 2  s .  co m

    if (!httpclient.isRunning()) {
        httpclient.start();
    }
}