List of usage examples for org.apache.commons.httpclient HttpConnectionManager getParams
public abstract HttpConnectionManagerParams getParams();
From source file:ke.go.moh.oec.adt.Daemon.java
private static boolean sendMessage(String url, String filename) { int returnStatus = HttpStatus.SC_CREATED; HttpClient httpclient = new HttpClient(); HttpConnectionManager connectionManager = httpclient.getHttpConnectionManager(); connectionManager.getParams().setSoTimeout(120000); PostMethod httpPost = new PostMethod(url); RequestEntity requestEntity;/*from ww w .j av a 2 s. com*/ try { FileInputStream message = new FileInputStream(filename); Base64InputStream message64 = new Base64InputStream(message, true, -1, null); requestEntity = new InputStreamRequestEntity(message64, "application/octet-stream"); } catch (FileNotFoundException e) { Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "File not found.", e); return false; } httpPost.setRequestEntity(requestEntity); try { httpclient.executeMethod(httpPost); returnStatus = httpPost.getStatusCode(); } catch (SocketTimeoutException e) { returnStatus = HttpStatus.SC_REQUEST_TIMEOUT; Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "Request timed out. Not retrying.", e); } catch (HttpException e) { returnStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR; Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "HTTP exception. Not retrying.", e); } catch (ConnectException e) { returnStatus = HttpStatus.SC_SERVICE_UNAVAILABLE; Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "Service unavailable. Not retrying.", e); } catch (UnknownHostException e) { returnStatus = HttpStatus.SC_NOT_FOUND; Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "Not found. Not retrying.", e); } catch (IOException e) { returnStatus = HttpStatus.SC_GATEWAY_TIMEOUT; Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "IO exception. Not retrying.", e); } finally { httpPost.releaseConnection(); } return returnStatus == HttpStatus.SC_OK; }
From source file:com.datos.vfs.provider.http.HttpClientFactory.java
/** * Creates a new connection to the server. * @param builder The HttpFileSystemConfigBuilder. * @param scheme The protocol.//from w ww . ja v a 2 s . c om * @param hostname The hostname. * @param port The port number. * @param username The username. * @param password The password * @param fileSystemOptions The file system options. * @return a new HttpClient connection. * @throws FileSystemException if an error occurs. * @since 2.0 */ public static HttpClient createConnection(final HttpFileSystemConfigBuilder builder, final String scheme, final String hostname, final int port, final String username, final String password, final FileSystemOptions fileSystemOptions) throws FileSystemException { HttpClient client; try { final HttpConnectionManager mgr = new MultiThreadedHttpConnectionManager(); final HttpConnectionManagerParams connectionMgrParams = mgr.getParams(); client = new HttpClient(mgr); final HostConfiguration config = new HostConfiguration(); config.setHost(hostname, port, scheme); if (fileSystemOptions != null) { final String proxyHost = builder.getProxyHost(fileSystemOptions); final int proxyPort = builder.getProxyPort(fileSystemOptions); if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) { config.setProxy(proxyHost, proxyPort); } final UserAuthenticator proxyAuth = builder.getProxyAuthenticator(fileSystemOptions); if (proxyAuth != null) { final UserAuthenticationData authData = UserAuthenticatorUtils.authenticate(proxyAuth, new UserAuthenticationData.Type[] { UserAuthenticationData.USERNAME, UserAuthenticationData.PASSWORD }); if (authData != null) { final UsernamePasswordCredentials proxyCreds = new UsernamePasswordCredentials( UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData, UserAuthenticationData.USERNAME, null)), UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData, UserAuthenticationData.PASSWORD, null))); final AuthScope scope = new AuthScope(proxyHost, AuthScope.ANY_PORT); client.getState().setProxyCredentials(scope, proxyCreds); } if (builder.isPreemptiveAuth(fileSystemOptions)) { final HttpClientParams httpClientParams = new HttpClientParams(); httpClientParams.setAuthenticationPreemptive(true); client.setParams(httpClientParams); } } final Cookie[] cookies = builder.getCookies(fileSystemOptions); if (cookies != null) { client.getState().addCookies(cookies); } } /** * ConnectionManager set methods must be called after the host & port and proxy host & port * are set in the HostConfiguration. They are all used as part of the key when HttpConnectionManagerParams * tries to locate the host configuration. */ connectionMgrParams.setMaxConnectionsPerHost(config, builder.getMaxConnectionsPerHost(fileSystemOptions)); connectionMgrParams.setMaxTotalConnections(builder.getMaxTotalConnections(fileSystemOptions)); connectionMgrParams.setConnectionTimeout(builder.getConnectionTimeout(fileSystemOptions)); connectionMgrParams.setSoTimeout(builder.getSoTimeout(fileSystemOptions)); client.setHostConfiguration(config); if (username != null) { final UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password); final AuthScope scope = new AuthScope(hostname, AuthScope.ANY_PORT); client.getState().setCredentials(scope, creds); } } catch (final Exception exc) { throw new FileSystemException("vfs.provider.http/connect.error", exc, hostname); } return client; }
From source file:it.geosolutions.geoserver.rest.HTTPUtils.java
/** * Send an HTTP request (PUT or POST) to a server. <BR> * Basic auth is used if both username and pw are not null. * <P>/* w w w. j a va2 s . com*/ * Only * <UL> * <LI>200: OK</LI> * <LI>201: ACCEPTED</LI> * <LI>202: CREATED</LI> * </UL> * are accepted as successful codes; in these cases the response string will * be returned. * * @return the HTTP response or <TT>null</TT> on errors. */ private static String send(final EntityEnclosingMethod httpMethod, String url, RequestEntity requestEntity, String username, String pw) { HttpClient client = new HttpClient(); HttpConnectionManager connectionManager = client.getHttpConnectionManager(); try { setAuth(client, url, username, pw); connectionManager.getParams().setConnectionTimeout(5000); if (requestEntity != null) httpMethod.setRequestEntity(requestEntity); int status = client.executeMethod(httpMethod); switch (status) { case HttpURLConnection.HTTP_OK: case HttpURLConnection.HTTP_CREATED: case HttpURLConnection.HTTP_ACCEPTED: String response = IOUtils.toString(httpMethod.getResponseBodyAsStream()); // LOGGER.info("================= POST " + url); if (LOGGER.isInfoEnabled()) LOGGER.info("HTTP " + httpMethod.getStatusText() + ": " + response); return response; default: LOGGER.warn("Bad response: code[" + status + "]" + " msg[" + httpMethod.getStatusText() + "]" + " url[" + url + "]" + " method[" + httpMethod.getClass().getSimpleName() + "]: " + IOUtils.toString(httpMethod.getResponseBodyAsStream())); return null; } } catch (ConnectException e) { LOGGER.info("Couldn't connect to [" + url + "]"); return null; } catch (IOException e) { LOGGER.error("Error talking to " + url + " : " + e.getLocalizedMessage()); return null; } finally { if (httpMethod != null) httpMethod.releaseConnection(); connectionManager.closeIdleConnections(0); } }
From source file:it.geosolutions.geoserver.rest.HTTPUtils.java
public static boolean httpPing(String url, String username, String pw) { GetMethod httpMethod = null;/*from w ww. j a va2 s. co m*/ HttpClient client = new HttpClient(); HttpConnectionManager connectionManager = client.getHttpConnectionManager(); try { setAuth(client, url, username, pw); httpMethod = new GetMethod(url); connectionManager.getParams().setConnectionTimeout(2000); int status = client.executeMethod(httpMethod); if (status != HttpStatus.SC_OK) { LOGGER.warn("PING failed at '" + url + "': (" + status + ") " + httpMethod.getStatusText()); return false; } else { return true; } } catch (ConnectException e) { return false; } catch (IOException e) { LOGGER.error(e.getLocalizedMessage(), e); return false; } finally { if (httpMethod != null) httpMethod.releaseConnection(); connectionManager.closeIdleConnections(0); } }
From source file:it.geosolutions.geoserver.rest.HTTPUtils.java
/** * Used to query for REST resources.//from w w w . j av a 2s . com * * @param url The URL of the REST resource to query about. * @param username * @param pw * @return true on 200, false on 404. * @throws RuntimeException on unhandled status or exceptions. */ public static boolean exists(String url, String username, String pw) { GetMethod httpMethod = null; HttpClient client = new HttpClient(); HttpConnectionManager connectionManager = client.getHttpConnectionManager(); try { setAuth(client, url, username, pw); httpMethod = new GetMethod(url); connectionManager.getParams().setConnectionTimeout(2000); int status = client.executeMethod(httpMethod); switch (status) { case HttpStatus.SC_OK: return true; case HttpStatus.SC_NOT_FOUND: return false; default: throw new RuntimeException("Unhandled response status at '" + url + "': (" + status + ") " + httpMethod.getStatusText()); } } catch (ConnectException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } finally { if (httpMethod != null) httpMethod.releaseConnection(); connectionManager.closeIdleConnections(0); } }
From source file:it.geosolutions.geoserver.rest.HTTPUtils.java
/** * Performs an HTTP GET on the given URL. <BR> * Basic auth is used if both username and pw are not null. * /* w w w .ja v a2 s . c om*/ * @param url The URL where to connect to. * @param username Basic auth credential. No basic auth if null. * @param pw Basic auth credential. No basic auth if null. * @return The HTTP response as a String if the HTTP response code was 200 * (OK). * @throws MalformedURLException */ public static String get(String url, String username, String pw) { GetMethod httpMethod = null; HttpClient client = new HttpClient(); HttpConnectionManager connectionManager = client.getHttpConnectionManager(); try { setAuth(client, url, username, pw); httpMethod = new GetMethod(url); connectionManager.getParams().setConnectionTimeout(5000); int status = client.executeMethod(httpMethod); if (status == HttpStatus.SC_OK) { InputStream is = httpMethod.getResponseBodyAsStream(); String response = IOUtils.toString(is); IOUtils.closeQuietly(is); if (response.trim().length() == 0) { // sometime gs rest fails LOGGER.warn("ResponseBody is empty"); return null; } else { return response; } } else { LOGGER.info("(" + status + ") " + HttpStatus.getStatusText(status) + " -- " + url); } } catch (ConnectException e) { LOGGER.info("Couldn't connect to [" + url + "]"); } catch (IOException e) { LOGGER.info("Error talking to [" + url + "]", e); } finally { if (httpMethod != null) httpMethod.releaseConnection(); connectionManager.closeIdleConnections(0); } return null; }
From source file:it.geosolutions.geoserver.rest.HTTPUtils.java
public static boolean delete(String url, final String user, final String pw) { DeleteMethod httpMethod = null;//from w ww.ja va 2 s . co m HttpClient client = new HttpClient(); HttpConnectionManager connectionManager = client.getHttpConnectionManager(); try { setAuth(client, url, user, pw); httpMethod = new DeleteMethod(url); connectionManager.getParams().setConnectionTimeout(5000); int status = client.executeMethod(httpMethod); String response = ""; if (status == HttpStatus.SC_OK) { InputStream is = httpMethod.getResponseBodyAsStream(); response = IOUtils.toString(is); IOUtils.closeQuietly(is); if (response.trim().equals("")) { if (LOGGER.isTraceEnabled()) LOGGER.trace( "ResponseBody is empty (this may be not an error since we just performed a DELETE call)"); return true; } if (LOGGER.isDebugEnabled()) LOGGER.debug("(" + status + ") " + httpMethod.getStatusText() + " -- " + url); return true; } else { LOGGER.info("(" + status + ") " + httpMethod.getStatusText() + " -- " + url); LOGGER.info("Response: '" + response + "'"); } } catch (ConnectException e) { LOGGER.info("Couldn't connect to [" + url + "]"); } catch (IOException e) { LOGGER.info("Error talking to [" + url + "]", e); } finally { if (httpMethod != null) httpMethod.releaseConnection(); connectionManager.closeIdleConnections(0); } return false; }
From source file:com.discursive.jccook.httpclient.MultithreadedExample.java
public void start() throws InterruptedException { HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams params = connectionManager.getParams(); params.setIntParameter(HttpConnectionManagerParams.MAX_HOST_CONNECTIONS, 2); params.setIntParameter(HttpConnectionManagerParams.MAX_TOTAL_CONNECTIONS, 4); List retrievers = new ArrayList(); for (int i = 0; i < 20; i++) { HttpClient client = new HttpClient(connectionManager); Thread thread = new Thread(new PageRetriever(client)); retrievers.add(thread);//from w w w . j a v a 2 s. com } Iterator threadIter = retrievers.iterator(); while (threadIter.hasNext()) { Thread thread = (Thread) threadIter.next(); thread.start(); } }
From source file:de.ingrid.iplug.opensearch.communication.OSCommunication.java
/** * Send a request with all parameters within the "url"-String. * /*from www . ja va 2s . c o m*/ * @param url is the URL to request including the parameters * @return the response of the request */ public InputStream sendRequest(String url) { try { HttpClientParams httpClientParams = new HttpClientParams(); HttpConnectionManager httpConnectionManager = new SimpleHttpConnectionManager(); httpClientParams.setSoTimeout(30 * 1000); httpConnectionManager.getParams().setConnectionTimeout(30 * 1000); httpConnectionManager.getParams().setSoTimeout(30 * 1000); HttpClient client = new HttpClient(httpClientParams, httpConnectionManager); method = new GetMethod(url); // set a request header // this can change in the result of the response since it might be // interpreted differently //method.addRequestHeader("Accept-Language", language); //"de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4"); int status = client.executeMethod(method); if (status == 200) { log.debug("Successfully received: " + url); return method.getResponseBodyAsStream(); } else { log.error("Response code for '" + url + "' was: " + status); return null; } } catch (HttpException e) { log.error("An HTTP-Exception occured when calling: " + url); e.printStackTrace(); } catch (IOException e) { log.error("An IO-Exception occured when calling: " + url); e.printStackTrace(); } return null; }
From source file:com.moss.jaxwslite.ServiceFactory.java
public synchronized void setConnectionTimeout(int timeout) { HttpConnectionManager manager = client.getHttpConnectionManager(); HttpConnectionManagerParams p = manager.getParams(); p.setConnectionTimeout(timeout);/* w w w .ja va 2 s . c o m*/ manager.setParams(p); }