List of usage examples for org.apache.commons.httpclient HttpClient setParams
public void setParams(HttpClientParams paramHttpClientParams)
From source file:edu.unc.lib.dl.ui.util.FileIOUtil.java
public static String postImport(HttpServletRequest request, String url) { Map<String, String[]> parameters = request.getParameterMap(); HttpClientParams params = new HttpClientParams(); params.setContentCharset("UTF-8"); HttpClient client = new HttpClient(); client.setParams(params); PostMethod post = new PostMethod(url); Iterator<Entry<String, String[]>> parameterIt = parameters.entrySet().iterator(); while (parameterIt.hasNext()) { Entry<String, String[]> parameter = parameterIt.next(); for (String parameterValue : parameter.getValue()) { post.addParameter(parameter.getKey(), parameterValue); }//from w ww.ja v a 2 s.c o m } try { client.executeMethod(post); return post.getResponseBodyAsString(); } catch (Exception e) { throw new ResourceNotFoundException("Failed to retrieve POST import request for " + url, e); } finally { post.releaseConnection(); } }
From source file:com.netsteadfast.greenstep.util.ApplicationSiteUtils.java
private static boolean checkTestConnection(String host, String contextPath, HttpServletRequest request) { boolean test = false; String basePath = request.getScheme() + "://" + host + "/" + contextPath; String urlStr = basePath + "/pages/system/testJsonResult.action"; try {/*w w w . ja v a 2s. c o m*/ logger.info("checkTestConnection , url=" + urlStr); HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(urlStr); HttpClientParams params = new HttpClientParams(); params.setConnectionManagerTimeout(TEST_JSON_HTTP_TIMEOUT); client.setParams(params); client.executeMethod(method); byte[] responseBody = method.getResponseBody(); if (null == responseBody) { test = false; return test; } String content = new String(responseBody, Constants.BASE_ENCODING); ObjectMapper mapper = new ObjectMapper(); @SuppressWarnings("unchecked") Map<String, Object> dataMap = (Map<String, Object>) mapper.readValue(content, HashMap.class); if (YesNo.YES.equals(dataMap.get("success"))) { test = true; } } catch (JsonParseException e) { logger.error(e.getMessage().toString()); } catch (JsonMappingException e) { logger.error(e.getMessage().toString()); } catch (Exception e) { e.printStackTrace(); } finally { if (!test) { logger.warn("checkTestConnection : " + String.valueOf(test)); } else { logger.info("checkTestConnection : " + String.valueOf(test)); } } return test; }
From source file:edu.unc.lib.dl.ui.service.DjatokaContentService.java
public void getMetadata(String simplepid, String datastream, OutputStream outStream, HttpServletResponse response, int retryServerError) { HttpClientParams params = new HttpClientParams(); params.setContentCharset("UTF-8"); HttpClient client = new HttpClient(); client.setParams(params); StringBuilder path = new StringBuilder(applicationPathSettings.getDjatokaPath()); path.append("resolver?url_ver=Z39.88-2004&rft_id=") .append(applicationPathSettings.getFedoraPathWithoutDefaultPort()).append("/objects/") .append(simplepid).append("/datastreams/").append(datastream).append("/content") .append("&svc_id=info:lanl-repo/svc/getMetadata"); GetMethod method = new GetMethod(path.toString()); try {//from w ww . jav a 2 s .c om client.executeMethod(method); if (method.getStatusCode() == HttpStatus.SC_OK) { if (response != null) { response.setHeader("Content-Type", "application/json"); response.setHeader("content-disposition", "inline"); FileIOUtil.stream(outStream, method); } } else { if ((method.getStatusCode() == 500 || method.getStatusCode() == 404) && retryServerError > 0) { this.getMetadata(simplepid, datastream, outStream, response, retryServerError - 1); } else { LOG.error("Unexpected failure: " + method.getStatusLine().toString()); LOG.error("Path was: " + method.getURI().getURI()); } } } catch (ClientAbortException e) { if (LOG.isDebugEnabled()) LOG.debug("User client aborted request to stream jp2 metadata for " + simplepid, e); } catch (Exception e) { LOG.error("Problem retrieving metadata for " + path, e); } finally { method.releaseConnection(); } }
From source file:com.feilong.tools.net.httpclient3.HttpClientUtil.java
/** * authentication./*w w w .j a v a 2 s .c om*/ * * @param httpMethod * the http method * @param httpClientConfig * the http client config * @param httpClient * the http client */ private static void setAuthentication(HttpMethod httpMethod, HttpClientConfig httpClientConfig, HttpClient httpClient) { UsernamePasswordCredentials usernamePasswordCredentials = httpClientConfig.getUsernamePasswordCredentials(); // ? if (Validator.isNotNullOrEmpty(usernamePasswordCredentials)) { httpMethod.setDoAuthentication(true); AuthScope authScope = AuthScope.ANY; Credentials credentials = usernamePasswordCredentials; httpClient.getState().setCredentials(authScope, credentials); // 1.1?(Preemptive Authentication) // ??HttpClientbasic????????? // ??? HttpClientParams httpClientParams = new HttpClientParams(); httpClientParams.setAuthenticationPreemptive(true); httpClient.setParams(httpClientParams); } }
From source file:com.yahoo.flowetl.services.http.BaseHttpGenerator.java
@Override public Pair<HttpClient, HttpMethod> generate(HttpParams in) { HttpClient c = new HttpClient(); c.getState().clear();//from ww w . j av a 2 s . c o m c.getHttpConnectionManager().setParams(getManagerParams(in)); c.setParams(getClientParams(in)); HttpMethod toCall = null; if (in instanceof HttpService.PostHttpParams) { // post?? toCall = getPostMethod(in); } else { // otherwise get (support more later??) toCall = getGetMethod(in); } applyCommonProperties(in, toCall); return new Pair<HttpClient, HttpMethod>(c, toCall); }
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 . j a v a 2 s . c o m * @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:com.twinsoft.convertigo.engine.util.HttpUtils.java
public static HttpClient makeHttpClient3(boolean usePool) { HttpClient httpClient; if (usePool) { MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); int maxTotalConnections = 100; try {//from w w w. j av a 2s. c om maxTotalConnections = new Integer( EnginePropertiesManager.getProperty(PropertyName.HTTP_CLIENT_MAX_TOTAL_CONNECTIONS)) .intValue(); } catch (NumberFormatException e) { Engine.logEngine.warn("Unable to retrieve the max number of connections; defaults to 100."); } int maxConnectionsPerHost = 50; try { maxConnectionsPerHost = new Integer( EnginePropertiesManager.getProperty(PropertyName.HTTP_CLIENT_MAX_CONNECTIONS_PER_HOST)) .intValue(); } catch (NumberFormatException e) { Engine.logEngine .warn("Unable to retrieve the max number of connections per host; defaults to 100."); } HttpConnectionManagerParams httpConnectionManagerParams = new HttpConnectionManagerParams(); httpConnectionManagerParams.setDefaultMaxConnectionsPerHost(maxConnectionsPerHost); httpConnectionManagerParams.setMaxTotalConnections(maxTotalConnections); connectionManager.setParams(httpConnectionManagerParams); httpClient = new HttpClient(connectionManager); } else { httpClient = new HttpClient(); } HttpClientParams httpClientParams = (HttpClientParams) HttpClientParams.getDefaultParams(); httpClientParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); /** #741 : belambra wants only one Set-Cookie header */ httpClientParams.setParameter("http.protocol.single-cookie-header", Boolean.TRUE); /** #5066 : httpClient auto retries failed request up to 3 times by default */ httpClientParams.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false)); httpClient.setParams(httpClientParams); return httpClient; }
From source file:com.motorola.studio.android.common.utilities.HttpUtils.java
private InputStream getInputStreamForUrl(String url, IProgressMonitor monitor, boolean returnStream) throws IOException { SubMonitor subMonitor = SubMonitor.convert(monitor); subMonitor.beginTask(UtilitiesNLS.HttpUtils_MonitorTask_PreparingConnection, 300); StudioLogger.debug(HttpUtils.class, "Verifying proxy usage for opening http connection"); //$NON-NLS-1$ // Try to retrieve proxy configuration to use if necessary IProxyService proxyService = ProxyManager.getProxyManager(); IProxyData proxyData = null;//from w w w . j av a2 s. c o m if (proxyService.isProxiesEnabled() || proxyService.isSystemProxiesEnabled()) { Authenticator.setDefault(new NetAuthenticator()); if (url.startsWith("https")) { proxyData = proxyService.getProxyData(IProxyData.HTTPS_PROXY_TYPE); StudioLogger.debug(HttpUtils.class, "Using https proxy"); //$NON-NLS-1$ } else if (url.startsWith("http")) { proxyData = proxyService.getProxyData(IProxyData.HTTP_PROXY_TYPE); StudioLogger.debug(HttpUtils.class, "Using http proxy"); //$NON-NLS-1$ } else { StudioLogger.debug(HttpUtils.class, "Not using any proxy"); //$NON-NLS-1$ } } // Creates the http client and the method to be executed HttpClient client = null; client = new HttpClient(); // If there is proxy data, work with it if (proxyData != null) { if (proxyData.getHost() != null) { // Sets proxy host and port, if any client.getHostConfiguration().setProxy(proxyData.getHost(), proxyData.getPort()); } if ((proxyData.getUserId() != null) && (proxyData.getUserId().trim().length() > 0)) { // Sets proxy user and password, if any Credentials cred = new UsernamePasswordCredentials(proxyData.getUserId(), proxyData.getPassword() == null ? "" : proxyData.getPassword()); //$NON-NLS-1$ client.getState().setProxyCredentials(AuthScope.ANY, cred); } } InputStream streamForUrl = null; getMethod = new GetMethod(url); getMethod.setFollowRedirects(true); // set a 30 seconds timeout HttpMethodParams params = getMethod.getParams(); params.setSoTimeout(15 * ONE_SECOND); getMethod.setParams(params); boolean trying = true; Credentials credentials = null; subMonitor.worked(100); subMonitor.setTaskName(UtilitiesNLS.HttpUtils_MonitorTask_ContactingSite); do { StudioLogger.info(HttpUtils.class, "Attempting to make a connection"); //$NON-NLS-1$ // retry to connect to the site once, also set the timeout for 5 seconds HttpClientParams clientParams = client.getParams(); clientParams.setIntParameter(HttpClientParams.MAX_REDIRECTS, 1); clientParams.setSoTimeout(5 * ONE_SECOND); client.setParams(clientParams); client.executeMethod(getMethod); if (subMonitor.isCanceled()) { break; } else { AuthState authorizationState = getMethod.getHostAuthState(); String authenticationRealm = authorizationState.getRealm(); if (getMethod.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { StudioLogger.debug(HttpUtils.class, "Client requested authentication; retrieving credentials"); //$NON-NLS-1$ credentials = authenticationRealmCache.get(authenticationRealm); if (credentials == null) { StudioLogger.debug(HttpUtils.class, "Credentials not found; prompting user for login/password"); //$NON-NLS-1$ subMonitor.setTaskName(UtilitiesNLS.HttpUtils_MonitorTask_WaitingAuthentication); LoginPasswordDialogCreator dialogCreator = new LoginPasswordDialogCreator(url); if (dialogCreator.openLoginPasswordDialog() == LoginPasswordDialogCreator.OK) { credentials = new UsernamePasswordCredentials(dialogCreator.getTypedLogin(), dialogCreator.getTypedPassword()); } else { // cancel pressed; stop trying trying = false; // set the monitor canceled to be able to stop process subMonitor.setCanceled(true); } } if (credentials != null) { AuthScope scope = new AuthScope(null, -1, authenticationRealm); client.getState().setCredentials(scope, credentials); } subMonitor.worked(100); } else if (getMethod.getStatusCode() == HttpStatus.SC_OK) { StudioLogger.debug(HttpUtils.class, "Http connection suceeded"); //$NON-NLS-1$ subMonitor.setTaskName(UtilitiesNLS.HttpUtils_MonitorTask_RetrievingSiteContent); if ((authenticationRealm != null) && (credentials != null)) { authenticationRealmCache.put(authenticationRealm, credentials); } else { // no authentication was necessary, just work the monitor subMonitor.worked(100); } StudioLogger.info(HttpUtils.class, "Retrieving site content"); //$NON-NLS-1$ // if the stream should not be returned (ex: only testing the connection is // possible), then null will be returned if (returnStream) { streamForUrl = getMethod.getResponseBodyAsStream(); } // succeeded; stop trying trying = false; subMonitor.worked(100); } else { // unhandled return status code trying = false; subMonitor.worked(200); } } } while (trying); subMonitor.done(); return streamForUrl; }
From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java
/** * Initializes the http client with correct httpmethod. Adds Authorization header to request. * @param client// w ww. j av a 2s . co m * @param uri * @param methodType * @return */ protected HttpMethod getInitializedHttpMethod(HttpClient client, String uri, HttpMethodType methodType) { Calendar now = GregorianCalendar.getInstance(); _apiSession.setLastRequestDateTimeUtc(new Date(now.getTimeInMillis())); _apiSession.setHash(CryptographyHelper.computeHash(_apiSession, _sharedSecret)); String authHeader = AuthorizationHelper.toAuthorizationHeader(_apiSession); HttpMethod method; switch (methodType) { case GET: method = new GetMethod(uri); break; case PUT: method = new PutMethod(uri); method.setRequestHeader("Content-Type", "text/xml"); break; case POST: method = new PostMethod(uri); method.setRequestHeader("Content-Type", "text/xml"); break; case DELETE: method = new DeleteMethod(uri); break; default: method = new GetMethod(uri); } HttpParams params = DefaultHttpParams.getDefaultParams(); method.setRequestHeader("Authorization", authHeader); client.setParams((HttpClientParams) params); return method; }
From source file:org.apache.nutch.indexer.solr.SolrUtils.java
public static CommonsHttpSolrServer getCommonsHttpSolrServer(JobConf job) throws MalformedURLException { HttpClient client = new HttpClient(); // Check for username/password if (job.getBoolean(SolrConstants.USE_AUTH, false)) { String username = job.get(SolrConstants.USERNAME); LOG.info("Authenticating as: " + username); AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthScope.ANY_SCHEME);//from www. j av a 2 s . co m client.getState().setCredentials(scope, new UsernamePasswordCredentials(username, job.get(SolrConstants.PASSWORD))); HttpClientParams params = client.getParams(); params.setAuthenticationPreemptive(true); client.setParams(params); } return new CommonsHttpSolrServer(job.get(SolrConstants.SERVER_URL), client); }