List of usage examples for org.apache.http.impl.client DefaultHttpClient getConnectionManager
public synchronized final ClientConnectionManager getConnectionManager()
From source file:com.alibaba.flink.utils.MetricsMonitor.java
public static Map httpResponse(String url) { Map ret;/*from w w w. j a v a 2s . co m*/ try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet getRequest = new HttpGet(url); getRequest.addHeader("accept", "application/json"); HttpResponse response = httpClient.execute(getRequest); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException( "Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } String data = EntityUtils.toString(response.getEntity()); ret = (Map) Utils.from_json(data); httpClient.getConnectionManager().shutdown(); } catch (IOException e) { ret = errorMsg(e.getMessage()); } return ret; }
From source file:com.mobicage.rogerthat.util.http.HTTPUtil.java
public static HttpClient getHttpClient(int connectionTimeout, int socketTimeout, final int retryCount) { final HttpParams params = new BasicHttpParams(); HttpConnectionParams.setStaleCheckingEnabled(params, true); HttpConnectionParams.setConnectionTimeout(params, connectionTimeout); HttpConnectionParams.setSoTimeout(params, socketTimeout); HttpClientParams.setRedirecting(params, false); final DefaultHttpClient httpClient = new DefaultHttpClient(params); if (shouldUseTruststore()) { KeyStore trustStore = loadTrustStore(); SSLSocketFactory socketFactory; try {//from w ww . j ava 2 s .c o m socketFactory = new SSLSocketFactory(null, null, trustStore); } catch (Exception e) { throw new RuntimeException(e); } socketFactory.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); Scheme sch = new Scheme("https", socketFactory, CloudConstants.HTTPS_PORT); httpClient.getConnectionManager().getSchemeRegistry().register(sch); } if (retryCount > 0) { httpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() { @Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { return executionCount < retryCount; } }); } return httpClient; }
From source file:ca.ualberta.cmput301w13t11.FoodBook.model.ServerClient.java
/** * Gets a thread safe client - that is, a client which can be used in a multithreaded * program and protects against certain errors that exist even in single threaded programs. * @return A Object of type DefaultHttpClient which will *//*from ww w . ja va 2s.c om*/ public static DefaultHttpClient getThreadSafeClient() { DefaultHttpClient client = new DefaultHttpClient(); ClientConnectionManager manager = client.getConnectionManager(); HttpParams params = client.getParams(); client = new DefaultHttpClient(new ThreadSafeClientConnManager(params, manager.getSchemeRegistry()), params); return client; }
From source file:ch.entwine.weblounge.test.util.TestSiteUtils.java
/** * Test for the correct response when etag header is set. * //from w w w .jav a2 s.com * @param request * the http request * @param eTagValue * the expected etag value * @param logger * used to log test output * @param params * the request parameters * @throws Exception * if processing the request fails */ public static void testETagHeader(HttpUriRequest request, String eTagValue, Logger logger, String[][] params) throws Exception { DefaultHttpClient httpClient = new DefaultHttpClient(); try { request.removeHeaders("If-Modified-Since"); request.setHeader("If-None-Match", eTagValue); logger.info("Sending 'If-None-Match' request to {}", request.getURI()); HttpResponse response = TestUtils.request(httpClient, request, params); assertEquals(HttpServletResponse.SC_NOT_MODIFIED, response.getStatusLine().getStatusCode()); assertNull(response.getEntity()); } finally { httpClient.getConnectionManager().shutdown(); } httpClient = new DefaultHttpClient(); try { request.removeHeaders("If-Modified-Since"); request.setHeader("If-None-Match", "\"abcdefghijklmt\""); logger.info("Sending 'If-None-Match' request to {}", request.getURI()); HttpResponse response = TestUtils.request(httpClient, request, params); assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); assertNotNull(response.getEntity()); response.getEntity().consumeContent(); } finally { httpClient.getConnectionManager().shutdown(); } }
From source file:org.broadinstitute.gatk.utils.help.ForumAPIUtils.java
private static String httpGet(String urlStr) { String output = ""; try {// w w w. j a v a 2 s . co m DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet getRequest = new HttpGet(urlStr); getRequest.addHeader("accept", "application/json"); HttpResponse response = httpClient.execute(getRequest); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException( "Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } output = IOUtils.toString(response.getEntity().getContent()); httpClient.getConnectionManager().shutdown(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return output; }
From source file:brooklyn.networking.cloudstack.HttpUtil.java
public static HttpClient createHttpClient(URI uri, Optional<Credentials> credentials) { final DefaultHttpClient httpClient = new DefaultHttpClient(); // TODO if supplier returns null, we may wish to defer initialization until url available? if (uri != null && "https".equalsIgnoreCase(uri.getScheme())) { try {//from w ww .j a v a 2 s . c o m int port = (uri.getPort() >= 0) ? uri.getPort() : 443; SSLSocketFactory socketFactory = new SSLSocketFactory(new TrustAllStrategy(), SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme sch = new Scheme("https", port, socketFactory); httpClient.getConnectionManager().getSchemeRegistry().register(sch); } catch (Exception e) { LOG.warn("Error in HTTP Feed of {}, setting trust for uri {}", uri); throw Exceptions.propagate(e); } } // Set credentials if (uri != null && credentials.isPresent()) { String hostname = uri.getHost(); int port = uri.getPort(); httpClient.getCredentialsProvider().setCredentials(new AuthScope(hostname, port), credentials.get()); } return httpClient; }
From source file:com.android.sdklib.internal.repository.UrlOpener.java
private static InputStream openWithHttpClient(String url, ITaskMonitor monitor) throws IOException, ClientProtocolException, CanceledByUserException { UserCredentials result = null;// w ww . ja v a 2s .c o m String realm = null; // use the simple one final DefaultHttpClient httpClient = new DefaultHttpClient(); // create local execution context HttpContext localContext = new BasicHttpContext(); HttpGet httpget = new HttpGet(url); // retrieve local java configured network in case there is the need to // authenticate a proxy ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); httpClient.setRoutePlanner(routePlanner); // Set preference order for authentication options. // In particular, we don't add AuthPolicy.SPNEGO, which is given preference over NTLM in // servers that support both, as it is more secure. However, we don't seem to handle it // very well, so we leave it off the list. // See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html for // more info. List<String> authpref = new ArrayList<String>(); authpref.add(AuthPolicy.BASIC); authpref.add(AuthPolicy.DIGEST); authpref.add(AuthPolicy.NTLM); httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref); httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref); boolean trying = true; // loop while the response is being fetched while (trying) { // connect and get status code HttpResponse response = httpClient.execute(httpget, localContext); int statusCode = response.getStatusLine().getStatusCode(); // check whether any authentication is required AuthState authenticationState = null; if (statusCode == HttpStatus.SC_UNAUTHORIZED) { // Target host authentication required authenticationState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE); } if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) { // Proxy authentication required authenticationState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE); } if (statusCode == HttpStatus.SC_OK) { // in case the status is OK and there is a realm and result, // cache it if (realm != null && result != null) { sRealmCache.put(realm, result); } } // there is the need for authentication if (authenticationState != null) { // get scope and realm AuthScope authScope = authenticationState.getAuthScope(); // If the current realm is different from the last one it means // a pass was performed successfully to the last URL, therefore // cache the last realm if (realm != null && !realm.equals(authScope.getRealm())) { sRealmCache.put(realm, result); } realm = authScope.getRealm(); // in case there is cache for this Realm, use it to authenticate if (sRealmCache.containsKey(realm)) { result = sRealmCache.get(realm); } else { // since there is no cache, request for login and password result = monitor.displayLoginCredentialsPrompt("Site Authentication", "Please login to the following domain: " + realm + "\n\nServer requiring authentication:\n" + authScope.getHost()); if (result == null) { throw new CanceledByUserException("User canceled login dialog."); } } // retrieve authentication data String user = result.getUserName(); String password = result.getPassword(); String workstation = result.getWorkstation(); String domain = result.getDomain(); // proceed in case there is indeed a user if (user != null && user.length() > 0) { Credentials credentials = new NTCredentials(user, password, workstation, domain); httpClient.getCredentialsProvider().setCredentials(authScope, credentials); trying = true; } else { trying = false; } } else { trying = false; } HttpEntity entity = response.getEntity(); if (entity != null) { if (trying) { // in case another pass to the Http Client will be performed, close the entity. entity.getContent().close(); } else { // since no pass to the Http Client is needed, retrieve the // entity's content. // Note: don't use something like a BufferedHttpEntity since it would consume // all content and store it in memory, resulting in an OutOfMemory exception // on a large download. return new FilterInputStream(entity.getContent()) { @Override public void close() throws IOException { super.close(); // since Http Client is no longer needed, close it httpClient.getConnectionManager().shutdown(); } }; } } } // We get here if we did not succeed. Callers do not expect a null result. httpClient.getConnectionManager().shutdown(); throw new FileNotFoundException(url); }
From source file:no.uib.tools.OnthologyHttpClient.java
private static BufferedReader getContentBufferedReader(String uri) { try {/*from w w w. j av a 2s . c o m*/ DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet getRequest = new HttpGet(uri); getRequest.addHeader("accept", "application/json"); HttpResponse response = httpClient.execute(getRequest); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Failed to quety the PSIMOD onthology : HTTP error code : " + response.getStatusLine().getStatusCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); httpClient.getConnectionManager().shutdown(); return br; } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:middleware.HTTPRequest.java
public static List<Vuelo> doGetVuelos() throws IOException { String result;/* www.jav a 2 s .c om*/ String url = "http://localhost:8084/MVIv2/webapi/vuelos"; DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet getRequest = new HttpGet(url); getRequest.addHeader("Accept", "application/json"); HttpResponse response = httpClient.execute(getRequest); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("ERROR AL CONSULTAR DEL TIPO: " + response.getStatusLine().getStatusCode()); } HttpEntity entity = response.getEntity(); result = EntityUtils.toString(entity); List<Vuelo> listaVuelos = getArrayVuelo(result); httpClient.getConnectionManager().shutdown(); return listaVuelos; }
From source file:middleware.HTTPRequest.java
public static List<Reserva> doGetReservas() throws IOException { String result;/*from w w w . java 2 s. c o m*/ String url = "http://localhost:8084/MVIv2/webapi/reservas"; DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet getRequest = new HttpGet(url); getRequest.addHeader("Accept", "application/json"); HttpResponse response = httpClient.execute(getRequest); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("ERROR AL CONSULTAR DEL TIPO: " + response.getStatusLine().getStatusCode()); } HttpEntity entity = response.getEntity(); result = EntityUtils.toString(entity); List<Reserva> listaReservas = getArrayReserva(result); httpClient.getConnectionManager().shutdown(); return listaReservas; }