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:com.ibm.subway.NewYorkSubway.java

public StationList getStationList(String routeId) throws Exception {
    logger.debug("Route {}", routeId);
    StationList returnedList = new StationList();

    try {/*from   w  w w . jav  a 2  s.co m*/
        if (routeId != null) {
            RequestConfig config = RequestConfig.custom().setSocketTimeout(10 * 1000)
                    .setConnectTimeout(10 * 1000).build();
            CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(config).build();

            URIBuilder builder = new URIBuilder();
            builder.setScheme("http").setHost(url).setPath("/by-route/" + routeId);
            URI uri = builder.build();
            HttpGet httpGet = new HttpGet(uri);
            httpGet.setHeader("Content-Type", "text/plain");

            HttpResponse httpResponse = httpclient.execute(httpGet);

            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                BufferedReader rd = new BufferedReader(
                        new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));

                // Read all the trains from the list
                ObjectMapper mapper = new ObjectMapper();
                returnedList = mapper.readValue(rd, StationList.class);
            } else {
                logger.error("could not get list from MTA http code {}",
                        httpResponse.getStatusLine().getStatusCode());
            }
        }
    } catch (Exception e) {
        logger.error("could not get list from MTA {}", e.getMessage());
        throw e;
    }

    return returnedList;
}

From source file:xyz.monotalk.social.mixcloud.Requester.java

/**
 * newHttpClient//  ww  w .  j  a  va  2s . co m
 *
 * @return
 */
private HttpClient newHttpClient() {
    // request configuration
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(2000).setSocketTimeout(2000).build();

    // headers
    List<Header> headers = new ArrayList<>();
    headers.add(new BasicHeader("Accept-Charset", "utf-8"));
    headers.add(new BasicHeader("Accept-Language", "ja, en;q=0.8"));
    headers.add(new BasicHeader("User-Agent", "Mozilla/5.0"));

    // create client
    HttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig)
            .setDefaultHeaders(headers).build();
    return httpClient;
}

From source file:com.mycompany.wolf.Room.java

public void removePlayer(String playerId) throws IOException {
    synchronized (mutex) {
        sessions.removeIf(equalityPredicate(playerId));
        List<Map<String, String>> roomInfo = sessions.stream()
                .map(s -> ImmutableMap.of("playerId", getPlayerId(s)))
                .collect(Collectors.toCollection(LinkedList::new));
        Map<String, Object> m = ImmutableMap.of("code", "exitResp", "properties", roomInfo);
        String json = new Gson().toJson(m);
        sessions.stream().forEach(s -> {
            s.getAsyncRemote().sendText(json);
        });/*w ww . j  av  a 2s.c o  m*/
    }
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultRequestConfig(requestConfig)
            .build();
    httpclient.start();
    try {
        String routerAddress = SpringContext.getBean("routerAddress");

        httpclient.execute(new HttpGet(routerAddress), new FutureCallback<HttpResponse>() {
            @Override
            public void completed(HttpResponse t) {
            }

            @Override
            public void failed(Exception excptn) {
            }

            @Override
            public void cancelled() {
            }
        });
    } finally {
        httpclient.close();
    }
}

From source file:microsoft.exchange.webservices.data.core.request.HttpClientWebRequest.java

/**
 * Prepares the request by setting appropriate headers, authentication, timeouts, etc.
 *///from  www .  j  a v a 2s. c  om
@Override
public void prepareConnection() {
    httpPost = new HttpPost(getUrl().toString());

    // Populate headers.
    httpPost.addHeader("Content-type", getContentType());
    httpPost.addHeader("User-Agent", getUserAgent());
    httpPost.addHeader("Accept", getAccept());
    httpPost.addHeader("Keep-Alive", "300");
    httpPost.addHeader("Connection", "Keep-Alive");

    if (isAcceptGzipEncoding()) {
        httpPost.addHeader("Accept-Encoding", "gzip,deflate");
    }

    if (getHeaders() != null) {
        for (Map.Entry<String, String> httpHeader : getHeaders().entrySet()) {
            httpPost.addHeader(httpHeader.getKey(), httpHeader.getValue());
        }
    }

    // Build request configuration.
    // Disable Kerberos in the preferred auth schemes - EWS should usually allow NTLM or Basic auth
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setAuthenticationEnabled(true)
            .setConnectionRequestTimeout(getTimeout()).setConnectTimeout(getTimeout())
            .setRedirectsEnabled(isAllowAutoRedirect()).setSocketTimeout(getTimeout())
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.BASIC))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.BASIC));

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

    // Add proxy credential if necessary.
    WebProxy proxy = getProxy();
    if (proxy != null) {
        HttpHost proxyHost = new HttpHost(proxy.getHost(), proxy.getPort());
        requestConfigBuilder.setProxy(proxyHost);

        if (proxy.hasCredentials()) {
            NTCredentials proxyCredentials = new NTCredentials(proxy.getCredentials().getUsername(),
                    proxy.getCredentials().getPassword(), "", proxy.getCredentials().getDomain());

            credentialsProvider.setCredentials(new AuthScope(proxyHost), proxyCredentials);
        }
    }

    // Add web service credential if necessary.
    if (isAllowAuthentication() && getUsername() != null) {
        NTCredentials webServiceCredentials = new NTCredentials(getUsername(), getPassword(), "", getDomain());
        credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY), webServiceCredentials);
    }

    httpContext.setCredentialsProvider(credentialsProvider);

    httpPost.setConfig(requestConfigBuilder.build());
}

From source file:org.yamj.core.tools.web.PoolingHttpClientBuilder.java

@SuppressWarnings("resource")
public PoolingHttpClient build() {
    // create proxy
    HttpHost proxy = null;// ww w .  ja  v a  2s.c om
    CredentialsProvider credentialsProvider = null;

    if (StringUtils.isNotBlank(proxyHost) && proxyPort > 0) {
        proxy = new HttpHost(proxyHost, proxyPort);

        if (StringUtils.isNotBlank(proxyUsername) && StringUtils.isNotBlank(proxyPassword)) {
            if (systemProperties) {
                credentialsProvider = new SystemDefaultCredentialsProvider();
            } else {
                credentialsProvider = new BasicCredentialsProvider();
            }
            credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                    new UsernamePasswordCredentials(proxyUsername, proxyPassword));
        }
    }

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
    connManager.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(socketTimeout).build());
    connManager.setMaxTotal(connectionsMaxTotal);
    connManager.setDefaultMaxPerRoute(connectionsMaxPerRoute);

    HttpClientBuilder builder = HttpClientBuilder.create().setConnectionManager(connManager).setProxy(proxy)
            .setDefaultCredentialsProvider(credentialsProvider)
            .setDefaultRequestConfig(RequestConfig.custom()
                    .setConnectionRequestTimeout(connectionRequestTimeout).setConnectTimeout(connectionTimeout)
                    .setSocketTimeout(socketTimeout).setProxy(proxy).build());

    // use system properties
    if (systemProperties) {
        builder.useSystemProperties();
    }

    // build the client
    PoolingHttpClient wrapper = new PoolingHttpClient(builder.build(), connManager);
    wrapper.addGroupLimit(".*", 1); // default limit, can be overwritten

    if (StringUtils.isNotBlank(maxDownloadSlots)) {
        LOG.debug("Using download limits: {}", maxDownloadSlots);

        Pattern pattern = Pattern.compile(",?\\s*([^=]+)=(\\d+)");
        Matcher matcher = pattern.matcher(maxDownloadSlots);
        while (matcher.find()) {
            String group = matcher.group(1);
            try {
                final Integer maxResults = Integer.valueOf(matcher.group(2));
                wrapper.addGroupLimit(group, maxResults);
                LOG.trace("Added download slot '{}' with max results {}", group, maxResults);
            } catch (NumberFormatException error) {
                LOG.debug("Rule '{}' is no valid regexp, ignored", group);
            }
        }
    }

    return wrapper;
}

From source file:org.springframework.remoting.httpinvoker.HttpComponentsHttpInvokerRequestExecutorTests.java

@Test
public void mergeBasedOnCurrentHttpClient() throws Exception {
    RequestConfig defaultConfig = RequestConfig.custom().setSocketTimeout(1234).build();
    final CloseableHttpClient client = mock(CloseableHttpClient.class,
            withSettings().extraInterfaces(Configurable.class));
    Configurable configurable = (Configurable) client;
    when(configurable.getConfig()).thenReturn(defaultConfig);

    HttpComponentsHttpInvokerRequestExecutor executor = new HttpComponentsHttpInvokerRequestExecutor() {
        @Override//from   w  w w .  ja v a 2  s . com
        public HttpClient getHttpClient() {
            return client;
        }
    };
    executor.setReadTimeout(5000);
    HttpInvokerClientConfiguration config = mockHttpInvokerClientConfiguration("http://fake-service");
    HttpPost httpPost = executor.createHttpPost(config);
    RequestConfig requestConfig = httpPost.getConfig();
    assertEquals(-1, requestConfig.getConnectTimeout());
    assertEquals(-1, requestConfig.getConnectionRequestTimeout());
    assertEquals(5000, requestConfig.getSocketTimeout());

    // Update the Http client so that it returns an updated  config
    RequestConfig updatedDefaultConfig = RequestConfig.custom().setConnectTimeout(1234).build();
    when(configurable.getConfig()).thenReturn(updatedDefaultConfig);
    executor.setReadTimeout(7000);
    HttpPost httpPost2 = executor.createHttpPost(config);
    RequestConfig requestConfig2 = httpPost2.getConfig();
    assertEquals(1234, requestConfig2.getConnectTimeout());
    assertEquals(-1, requestConfig2.getConnectionRequestTimeout());
    assertEquals(7000, requestConfig2.getSocketTimeout());
}

From source file:com.comcast.cdn.traffic_control.traffic_router.neustar.data.NeustarDatabaseUpdater.java

public CloseableHttpResponse getRemoteDataResponse(URI uri) {
    HttpGet httpGet = new HttpGet(uri);
    httpGet.setConfig(RequestConfig.custom().setSocketTimeout(neustarPollingTimeout).build());
    Date buildDate = getDatabaseBuildDate();

    if (buildDate != null) {
        httpGet.setHeader("If-Modified-Since",
                new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z").format(buildDate));
    }/*from   ww  w .  j a v  a  2 s. com*/

    return httpClient.execute(httpGet);
}

From source file:tradeok.HttpTool.java

public static String postJsonBody(String url, int timeout, Map<String, Object> map, String encoding)
        throws Exception {
    HttpPost post = new HttpPost(url);
    try {//from ww w  .  j a  v  a 2s .c o m
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout)
                .setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setExpectContinueEnabled(false)
                .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build();
        post.setConfig(requestConfig);
        post.setHeader("User-Agent", USER_AGENT);
        post.setHeader("Accept",
                "text/html,application/xhtml+xml,application/json,application/xml;q=0.9,*/*;q=0.8");
        post.setHeader("Connection", "keep-alive");
        post.setHeader("Content-Type", "application/json; charset=UTF-8");

        String str1 = object2json(map).replace("\\", "");
        post.setEntity(new StringEntity(str1, encoding));
        CloseableHttpResponse response = httpclient.execute(post);
        try {
            HttpEntity entity = response.getEntity();
            try {
                if (entity != null) {
                    String str = EntityUtils.toString(entity, encoding);
                    return str;
                }
            } finally {
                if (entity != null) {
                    entity.getContent().close();
                }
            }
        } finally {
            if (response != null) {
                response.close();
            }
        }
    } finally {
        post.releaseConnection();
    }
    return "";
}