Example usage for org.apache.http.client.config RequestConfig custom

List of usage examples for org.apache.http.client.config RequestConfig custom

Introduction

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

Prototype

public static RequestConfig.Builder custom() 

Source Link

Usage

From source file:dal.arris.RequestArrisAlter.java

public RequestArrisAlter(Integer deviceId, Autenticacao autenticacao, String frequency)
        throws UnsupportedEncodingException, IOException {
    Autenticacao a = AuthFactory.getEnd();
    String auth = a.getUser() + ":" + a.getPassword();
    String url = a.getLink() + "capability/execute?capability="
            + URLEncoder.encode("\"getLanWiFiInfo\"", "UTF-8") + "&deviceId=" + deviceId + "&input="
            + URLEncoder.encode(frequency, "UTF-8");

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(1);// w  w  w.j a v a2  s .com
    cm.setDefaultMaxPerRoute(1);
    HttpHost localhost = new HttpHost("10.200.6.150", 80);
    cm.setMaxPerRoute(new HttpRoute(localhost), 50);

    // Cookies
    RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

    CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm)
            .setDefaultRequestConfig(globalConfig).build();

    byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("UTF-8")));
    String authHeader = "Basic " + new String(encodedAuth);

    //        CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpGet httpget = new HttpGet(url);
        httpget.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
        httpget.setHeader(HttpHeaders.CONTENT_TYPE, "text/html");
        httpget.setHeader("Cookie", "JSESSIONID=aaazqNDcHoduPbavRvVUv; AX-CARE-AGENTS-20480=HECDMIAKJABP");

        RequestConfig localConfig = RequestConfig.copy(globalConfig).setCookieSpec(CookieSpecs.STANDARD_STRICT)
                .build();

        HttpGet httpGet = new HttpGet("/");
        httpGet.setConfig(localConfig);

        //            httpget.setHeader(n);
        System.out.println("Executing request " + httpget.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpget);

        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());

            // Get hold of the response entity
            HttpEntity entity = response.getEntity();

            // If the response does not enclose an entity, there is no need
            // to bother about connection release
            if (entity != null) {
                InputStream instream = entity.getContent();
                try {
                    instream.read();
                    BufferedReader rd = new BufferedReader(
                            new InputStreamReader(response.getEntity().getContent()));
                    String line = "";
                    while ((line = rd.readLine()) != null) {
                        System.out.println(line);
                    }
                    // do something useful with the response
                } catch (IOException ex) {
                    // In case of an IOException the connection will be released
                    // back to the connection manager automatically
                    throw ex;
                } finally {
                    // Closing the input stream will trigger connection release
                    instream.close();
                }
            }
        } finally {
            response.close();
            for (Header allHeader : response.getAllHeaders()) {
                System.out.println("Nome: " + allHeader.getName() + " Valor: " + allHeader.getValue());
            }
        }
    } finally {
        httpclient.close();
    }
    httpclient.close();
}

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

@Override
public Authentication attemptAuthentication(final HttpServletRequest request,
        final HttpServletResponse response) {
    final String token = request.getParameter("token");

    if (token != null) {
        // Token is the last part of URL

        // First get the cookie
        final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
        clientBuilder.setDefaultRequestConfig(
                RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).build());

        // Do the POST
        try (CloseableHttpClient httpClient = clientBuilder.build()) {
            final HttpPost httpPost = new HttpPost(getSsoPostUrl());
            httpPost.setEntity(new StringEntity(token, StandardCharsets.UTF_8.name()));
            httpPost.setHeader("Content-Type", "application/json");
            final HttpResponse httpResponse = httpClient.execute(httpPost);
            if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()) {
                return getAuthenticationManager().authenticate(new UsernamePasswordAuthenticationToken(
                        EntityUtils.toString(httpResponse.getEntity()), "N/A", new ArrayList<>()));
            }/*from  ww w  .  java 2s .com*/
        } catch (final IOException e) {
            log.warn("Local SSO server is not available", e);
        }

    }
    throw new BadCredentialsException("Invalid user or password");
}

From source file:com.scoopit.weedfs.client.WeedFSClientBuilder.java

public WeedFSClient build() {
    if (masterUrl == null) {
        try {/*from  w  w  w .  ja  v a  2  s  .c  om*/
            // default url for testing purpose
            masterUrl = new URL("http://localhost:9333");
        } catch (MalformedURLException e) {
            // This cannot happen by construction
            throw new Error(e);
        }
    }

    if (httpClient == null) {
        // minimal http client
        RequestConfig config = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();

        httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
    }

    return new WeedFSClientImpl(masterUrl, httpClient, lookupCache);
}

From source file:network.thunder.client.communications.HTTPS.java

public boolean connect(String URL) {
    try {/*from w  w  w  . j a  va 2  s.c  o m*/

        RequestConfig.custom().setConnectTimeout(10 * 1000).build();
        httpClient = HttpClients.createDefault();

        httpGet = new HttpGet(URL);
        httpResponse = httpClient.execute(httpGet);

        return true;

    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:org.springframework.cloud.config.server.support.HttpClientSupport.java

public static HttpClientBuilder builder(HttpEnvironmentRepositoryProperties environmentProperties)
        throws GeneralSecurityException {
    SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    if (environmentProperties.isSkipSslValidation()) {
        sslContextBuilder.loadTrustMaterial(null, (certificate, authType) -> true);
        httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier());
    }//  ww w .jav a  2 s.  c  o m

    if (!CollectionUtils.isEmpty(environmentProperties.getProxy())) {
        ProxyHostProperties httpsProxy = environmentProperties.getProxy()
                .get(ProxyHostProperties.ProxyForScheme.HTTPS);
        ProxyHostProperties httpProxy = environmentProperties.getProxy()
                .get(ProxyHostProperties.ProxyForScheme.HTTP);

        httpClientBuilder.setRoutePlanner(new SchemeBasedRoutePlanner(httpsProxy, httpProxy));
        httpClientBuilder
                .setDefaultCredentialsProvider(new ProxyHostCredentialsProvider(httpProxy, httpsProxy));
    } else {
        httpClientBuilder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()));
        httpClientBuilder.setDefaultCredentialsProvider(new SystemDefaultCredentialsProvider());
    }

    int timeout = environmentProperties.getTimeout() * 1000;
    return httpClientBuilder.setSSLContext(sslContextBuilder.build()).setDefaultRequestConfig(
            RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build());
}

From source file:noiter.arch.restful.service.payment.SyncPaymentService.java

public SyncPaymentService() {
    ClientConfig clientConfig = new ClientConfig(); // jersey specific
    clientConfig.connectorProvider(new ApacheConnectorProvider()); // jersey specific

    RequestConfig reqConfig = RequestConfig.custom() // apache HttpClient specific
            .setConnectTimeout(1000).setSocketTimeout(1000).setConnectionRequestTimeout(100).build();

    clientConfig.property(ApacheClientProperties.REQUEST_CONFIG, reqConfig); // jersey specific

    client = ClientBuilder.newClient(clientConfig);
    client.register(new ClientCircuitBreakerFilter());

    paymentDao = new PaymentDaoImpl();
}

From source file:eu.eexcess.partnerdata.reference.enrichment.DbpediaSpotlight.java

public boolean isEntityDbpediaSpotlight(String word, PartnerdataLogger logger) {
    long startTime = logger.getActLogEntry().getTimeNow();
    try {/*  ww w  .j  a  v  a2s . c o m*/
        String URL = DBPEDIA_URL;
        URL += word.replaceAll(" ", "%20");

        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout)
                .setSocketTimeout(timeout).build();
        HttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();

        //      HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(URL);
        request.setHeader("Accept", "text/xml");
        HttpResponse response;

        try {
            response = client.execute(request);
            if (response.getStatusLine().getStatusCode() == 200) {
                InputStream is = response.getEntity().getContent();
                //               Set<DbpediaSpotlightResult> entities=XmlParser.getEntitiesDbpediaSpotlightCandidatesXML(this.partnerConfig,is);
                Set<DbpediaSpotlightResult> entities = XmlParser
                        .getEntitiesDbpediaSpotlightAnnotateXML(this.partnerConfig, is, logger);
                is.close();
                logger.getActLogEntry().addEnrichmentDbpediaSpotlightResults(entities.size());
                logger.getActLogEntry().addEnrichmentDbpediaSpotlightServiceCalls(1);
                logger.getActLogEntry().addEnrichmentDbpediaSpotlightServiceCallDuration(startTime);

                return entities.size() > 0;
            }

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (RuntimeException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

    }

    return false;

}

From source file:apidemo.APIDemo.java

public static String sendPostJson(String postUrl, String jsonContent, int timeout /*milisecond*/)
        throws Exception {
    RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(timeout)
            .setConnectTimeout(timeout).build();
    try (CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig)
            .build()) {/*from w  ww .  j av  a 2 s. c o m*/
        HttpPost httpPost = new HttpPost(postUrl);
        StringEntity input = new StringEntity(jsonContent, "UTF-8");
        input.setContentType("application/json");
        httpPost.setEntity(input);
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            if (response.getStatusLine().getStatusCode() != 200) {
                throw new IOException("Failed : HTTP getStatusCode: " + response.getStatusLine().getStatusCode()
                        + " HTTP getReasonPhrase: " + response.getStatusLine().getReasonPhrase());
            }
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader((response.getEntity().getContent())))) {
                String output;
                StringBuilder strBuilder = new StringBuilder();
                while ((output = br.readLine()) != null) {
                    strBuilder.append(output);
                }
                return strBuilder.toString();
            }
        }
    }
}

From source file:io.logspace.agent.hq.HqClient.java

public HqClient(String baseUrl, String agentControllerId, String spaceToken) {
    super();/*w w w.  j ava  2  s  . co m*/

    this.baseUrl = baseUrl;
    if (this.baseUrl == null || this.baseUrl.trim().length() == 0) {
        throw new AgentControllerInitializationException("The base URL must not be empty!");
    }

    this.agentControllerId = agentControllerId;
    this.spaceToken = spaceToken;

    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(TIMEOUT)
            .setConnectTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build();

    Set<? extends Header> defaultHeaders = Collections
            .singleton(new BasicHeader("Accept", APPLICATION_JSON.getMimeType()));

    this.httpClient = HttpClients.custom().disableAutomaticRetries().setDefaultRequestConfig(requestConfig)
            .setDefaultHeaders(defaultHeaders).build();
}