List of usage examples for org.apache.http.client.config RequestConfig custom
public static RequestConfig.Builder custom()
From source file:com.lixiaocong.util.weather.WeatherHelper.java
public static Weather getWeather(String city) throws IOException { HttpClient httpClient = HttpClients.custom().build(); HttpGet httpGet = new HttpGet("http://apis.baidu.com/apistore/weatherservice/weather?citypinyin=" + city); httpGet.addHeader("apikey", "f6e1b7c306d087df20761632655bc18b"); RequestConfig config = RequestConfig.custom().setConnectTimeout(500).build(); httpGet.setConfig(config);//from ww w . j a v a2 s . com HttpResponse response = httpClient.execute(httpGet); String jsonString = EntityUtils.toString(response.getEntity()); logger.info("weather server returns " + jsonString); ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(jsonString, Weather.class); }
From source file:com.cloud.utils.rest.HttpClientHelper.java
public static CloseableHttpClient createHttpClient(final int maxRedirects) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException { final Registry<ConnectionSocketFactory> socketFactoryRegistry = createSocketFactoryConfigration(); final BasicCookieStore cookieStore = new BasicCookieStore(); return HttpClientBuilder.create() .setConnectionManager(new PoolingHttpClientConnectionManager(socketFactoryRegistry)) .setRedirectStrategy(new LaxRedirectStrategy()) .setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT) .setMaxRedirects(maxRedirects).build()) .setDefaultCookieStore(cookieStore).setRetryHandler(new StandardHttpRequestRetryHandler()).build(); }
From source file:com.microsoft.azure.keyvault.authentication.BearerAuthenticationSetup.java
/** * Configures a {@link HttpClientBuilder} to call the informed * {@link BearerCredentialsSupport} object to answer "bearer" challenges, * such as <code>401 Unauthorized</code> responses. The * {@link BearerCredentialsSupport} object can return a token an hide * <code>401</code> results from users. *//*from w ww .ja va 2 s. c o m*/ public static void configureClientBuilder(HttpClientBuilder httpBuilder, BearerCredentialsSupport support) { // Configure to use "bearer" as preferred authentication scheme (without // this, the client uses basic, diggest, etc). Builder configBuilder = RequestConfig.custom() .setTargetPreferredAuthSchemes(Arrays.asList(new String[] { BearerAuthentication.NAME })); httpBuilder.setDefaultRequestConfig(configBuilder.build()); // Provide a custom "bearer" authentication provider. RegistryBuilder<AuthSchemeProvider> schemeProviderBuilder = RegistryBuilder.create(); schemeProviderBuilder.register(BearerAuthentication.NAME, BearerAuthenticationProvider.INSTANCE); httpBuilder.setDefaultAuthSchemeRegistry(schemeProviderBuilder.build()); // Configure to use the CloudCredentialsProvider. httpBuilder.setDefaultCredentialsProvider(new BearerCredentialsProvider(support)); }
From source file:zz.pseas.ghost.client.ClientFactory.java
public static CloseableHttpClient getNewClient() { try {//from w ww . j a v a 2 s . c o m SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext); Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslsf) .build(); PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(reg); RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10 * 60 * 1000) .setConnectionRequestTimeout(10 * 60 * 1000).setConnectionRequestTimeout(10 * 60 * 1000) .build(); CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(requestConfig) .setConnectionManager(connMgr).build(); return client; } catch (Exception e) { return null; } }
From source file:sce.HTTPPostReq.java
HttpPost createConnectivity(String restUrl, String username, String password, int timeout) { HttpPost post = new HttpPost(restUrl); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout) .setConnectionRequestTimeout(timeout).build(); post.setConfig(requestConfig);/*from ww w . ja v a 2 s . c om*/ if (username != null && password != null) { String auth = new StringBuffer(username).append(":").append(password).toString(); byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII"))); String authHeader = "Basic " + new String(encodedAuth); post.setHeader("AUTHORIZATION", authHeader); } post.setHeader("Content-Type", "application/json"); post.setHeader("Accept", "application/json"); post.setHeader("Accept-Enconding", "UTF-8"); post.setHeader("X-Stream", "true"); return post; }
From source file:no.difi.vefa.peppol.lookup.fetcher.BasicApacheFetcher.java
public BasicApacheFetcher(Mode mode) { super(mode);//from w w w. jav a 2 s. c o m this.requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout).setConnectTimeout(timeout) .setSocketTimeout(timeout).build(); }
From source file:com.beginner.core.utils.HttpUtil.java
/** * <p>To request the POST way.</p> * /*from ww w . j a v a 2 s. co m*/ * @param url request URI * @param json request parameter(json format string) * @param timeout request timeout time in milliseconds(The default timeout time for 30 seconds.) * @return String response result * @throws Exception * @since 1.0.0 */ public static String post(String url, String json, Integer timeout) throws Exception { // Validates input if (StringUtils.isBlank(url)) throw new IllegalArgumentException("The url cannot be null and cannot be empty."); //The default timeout time for 30 seconds if (null == timeout) timeout = 30000; String result = null; CloseableHttpClient httpClient = null; CloseableHttpResponse httpResponse = null; try { httpClient = HttpClients.createDefault(); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout) .setConnectTimeout(timeout).build(); HttpPost httpPost = new HttpPost(url); httpPost.setConfig(requestConfig); httpPost.setHeader("Content-Type", "text/plain"); httpPost.setEntity(new StringEntity(json, "UTF-8")); httpResponse = httpClient.execute(httpPost); HttpEntity entity = httpResponse.getEntity(); result = EntityUtils.toString(entity); EntityUtils.consume(entity); } catch (Exception e) { logger.error("POST?", e); return null; } finally { if (null != httpResponse) httpResponse.close(); if (null != httpClient) httpClient.close(); } return result; }
From source file:org.apache.ambari.view.internal.WSProvider.java
private ClientHttpRequestFactory getClientHttpRequestFactory() { int timeout = 5000; RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout) .setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build(); CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build(); return new HttpComponentsClientHttpRequestFactory(client); }
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); }//from ww w. j a v a 2 s .co m 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:org.artifactory.util.HttpClientUtils.java
/** * Creates a custom configuration for the request based on the default client configuration. * Http client will disregard the default client configuration if a request contains specific configuration. So it * important to copy from the client default config and not just creating a plain new config. * * @param client The client expected to run this request * @param request The request for the custom config * @return Request configuration builder based on the client defaults ot the already existing request config. *///from www .j a va 2 s. co m public static RequestConfig.Builder copyOrCreateConfig(@Nonnull HttpClient client, HttpRequestBase request) { if (request.getConfig() != null) { // request already has custom config -> copy from it return RequestConfig.copy(request.getConfig()); } RequestConfig defaultConfig = getDefaultConfig(client); if (defaultConfig != null) { // create based on the client default config return RequestConfig.copy(defaultConfig); } else { return RequestConfig.custom(); } }