List of usage examples for org.apache.http.client.config RequestConfig custom
public static RequestConfig.Builder custom()
From source file:org.fcrepo.apix.registry.impl.HttpClientFactory.java
/** * Construct a new HttpClient./*from w w w . j a v a 2 s . c o m*/ * * @return HttpClient impl. */ public CloseableHttpClient getClient() { final RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTimeout) .setSocketTimeout(socketTimeout).build(); return HttpClientBuilder.create().setDefaultRequestConfig(config).build(); }
From source file:network.HttpClientAdaptor.java
public String doGet(String url) { try {//from ww w . j ava 2 s . c om HttpGet httpGet = new HttpGet(url); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout) .setConnectTimeout(timeout).setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build();//?????????? httpGet.setConfig(requestConfig); CloseableHttpResponse response = this.httpclient.execute(httpGet, localContext); BufferedReader br = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), this.encode)); String htmlStr = null; int c = 0; StringBuilder temp = new StringBuilder(); while ((c = br.read()) != -1) { temp.append((char) c); } htmlStr = temp.toString(); httpGet.releaseConnection(); httpGet.completed(); return htmlStr; } catch (IOException ex) { Logger.getLogger(HttpClientAdaptor.class.getName()).log(Level.SEVERE, null, ex); } return null; }
From source file:co.paralleluniverse.fibers.dropwizard.FiberDropwizardTest.java
@Before public void setUp() throws Exception { this.client = HttpClients.custom().setDefaultRequestConfig(RequestConfig.custom().setSocketTimeout(TIMEOUT) .setConnectTimeout(TIMEOUT).setConnectionRequestTimeout(TIMEOUT).build()).build(); }
From source file:org.apache.maven.wagon.providers.http.HttpClientWagonTest.java
public void testSetMaxRedirectsParamViaConfig() { HttpMethodConfiguration methodConfig = new HttpMethodConfiguration(); int maxRedirects = 2; methodConfig.addParam("http.protocol.max-redirects", "%i," + maxRedirects); HttpConfiguration config = new HttpConfiguration(); config.setAll(methodConfig);/*from w w w .j a v a 2 s . c o m*/ HttpHead method = new HttpHead(); RequestConfig.Builder builder = RequestConfig.custom(); ConfigurationUtils.copyConfig(config.getMethodConfiguration(method), builder); RequestConfig requestConfig = builder.build(); assertEquals(2, requestConfig.getMaxRedirects()); }
From source file:org.tnova.service.catalog.client.RestTemplateFactory.java
@Override public void afterPropertiesSet() throws Exception { final int timeout = 5; final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout * 1000) .setSocketTimeout(timeout * 1000).build(); final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM), new UsernamePasswordCredentials("user1", "user1Pass")); final CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig) .setDefaultCredentialsProvider(credentialsProvider).build(); final ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(client); restTemplate = new RestTemplate(requestFactory); }
From source file:de.freegroup.twogo.plotter.rpc.Client.java
public JSONObject sendAndReceive(String endpoint, String method, Object[] args) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); RequestConfig config = RequestConfig.custom() // .setProxy(proxy) .build();/*from ww w . ja va 2 s . c o m*/ HttpPost request = new HttpPost(this.serverUrl + endpoint); request.setConfig(config); request.setHeader("Content-Type", "application/json"); request.setHeader("X-CSRF-Token", getToken(httpclient)); JSONObject message = buildParam(method, args); StringEntity body = new StringEntity(message.toString(), ContentType.create("application/json", Consts.UTF_8)); request.setEntity(body); System.out.println(">> Request URI: " + request.getRequestLine().getUri()); try { CloseableHttpResponse response = httpclient.execute(request); JSONTokener tokener = new JSONTokener(new BasicResponseHandler().handleResponse(response)); Object rawResponseMessage = tokener.nextValue(); JSONObject responseMessage = (JSONObject) rawResponseMessage; if (responseMessage == null) { throw new ClientError("Invalid response type - " + rawResponseMessage.getClass()); } return responseMessage; } catch (Exception e) { throw new ClientError(e); } }
From source file:tv.icntv.common.HttpClientUtil.java
/** * Get content by url as string//from w w w.j a v a2s. c om * * @param url original url * @return page content * @throws java.io.IOException */ public static String getContent(String url) throws IOException { // construct request HttpGet request = new HttpGet(url); request.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")); request.setConfig(RequestConfig.custom().setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT) .setSocketTimeout(SOCKET_TIMEOUT).build()); // construct response handler ResponseHandler<String> handler = new ResponseHandler<String>() { @Override public String handleResponse(final HttpResponse response) throws IOException { StatusLine status = response.getStatusLine(); // status if (status.getStatusCode() != HttpStatus.SC_OK) { throw new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()); } // get encoding in header String encoding = getPageEncoding(response); boolean encodingFounded = true; if (Strings.isNullOrEmpty(encoding)) { encodingFounded = false; encoding = "iso-8859-1"; } // get content and find real encoding HttpEntity entity = response.getEntity(); if (entity == null) { return null; } // get content byte[] contentBytes = EntityUtils.toByteArray(entity); if (contentBytes == null) { return null; } // found encoding if (encodingFounded) { return new String(contentBytes, encoding); } // attempt to discover encoding String rawContent = new String(contentBytes, DEFAULT_ENCODING); Matcher matcher = PATTERN_HTML_CHARSET.matcher(rawContent); if (matcher.find()) { String realEncoding = matcher.group(1); if (!encoding.equalsIgnoreCase(realEncoding)) { // bad luck :( return new String(rawContent.getBytes(encoding), realEncoding); } } // not found right encoding :) return rawContent; } }; // execute CloseableHttpClient client = HttpClientHolder.getClient(); return client.execute(request, handler); }
From source file:org.wisdom.test.http.Options.java
/** * Refreshes the options, and restores defaults. *//*from w ww . j a v a 2 s . co 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:nl.architolk.ldt.processors.HttpClientProperties.java
private static void initialize() throws Exception { notInitialized = false;//from www. j ava2 s.c o m //Fetch property-values PropertySet props = Properties.instance().getPropertySet(); String proxyHost = props.getString("oxf.http.proxy.host"); Integer proxyPort = props.getInteger("oxf.http.proxy.port"); proxyExclude = props.getString("oxf.http.proxy.exclude"); String sslKeystoreURI = props.getStringOrURIAsString("oxf.http.ssl.keystore.uri", false); String sslKeystorePassword = props.getString("oxf.http.ssl.keystore.password"); //Create custom scheme if needed if (sslKeystoreURI != null && sslKeystorePassword != null) { SSLContext sslcontext = SSLContexts.custom() .loadTrustMaterial(new URL(sslKeystoreURI), sslKeystorePassword.toCharArray()).build(); sslsf = new SSLConnectionSocketFactory(sslcontext); } //Create requestConfig proxy if needed if (proxyHost != null && proxyPort != null) { requestConfig = RequestConfig.custom().setProxy(new HttpHost(proxyHost, proxyPort, "http")).build(); } }