List of usage examples for org.apache.commons.httpclient HttpClient getParams
public HttpClientParams getParams()
From source file:org.josso.test.support.TckTestSupport.java
/** * Take a look at http://hc.apache.org/httpclient-3.x/preference-api.html for more details *///w ww.jav a 2s .co m protected HttpClient doMakeClient() { HttpClient c = new HttpClient(); c.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); c.getParams().setBooleanParameter("http.protocol.allow-circular-redirects", true); return c; }
From source file:org.kalypso.commons.net.ProxyUtilities.java
/** * Creates a configured http client. The configuration includes setting of proxy settings. * <p>//from w w w . j ava 2s. c om * IMPORTANT: To use proxy-authentication, you must use the setDoAuthentication Method of the HttpMethod you are going * to use. * </p> * <strong>Example:</strong> * * <pre> * HttpMethod method = new GetMethod( m_url.toString() ); * method.setDoAuthentication( true ); * </pre> * * @param timeout * The socket timeout in milliseconds. * @param retries * The number of retries, the http client is going to make. Set to a value lower then 0 to leave it at the * default value. * @return The configured http client. If no proxy is set, it will be a normal http client with the given timeout and * retries. * @deprecated This method should not be used any more, because its functionality is covered completely by the method * {@link #getConfiguredHttpClient(int, URL, int)}. If you have no appropriate URL, leave it null. */ @Deprecated public static HttpClient getConfiguredHttpClient(final int timeout, final int retries) { /* Create the new http client. */ final HttpClient client = new HttpClient(); /* Client should always authenticate before making a connection. */ client.getParams().setAuthenticationPreemptive(true); client.getParams().setSoTimeout(timeout); /* If a retry count is given, set the number of retries. */ if (retries >= 0) client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(retries, true)); /* Get the proxy object. */ final Proxy proxy = getProxy(); /* If the proxy should be used, configure the client with it. */ if (proxy.useProxy()) { /* Get the proxy data. */ final String proxyHost = proxy.getProxyHost(); final int proxyPort = proxy.getProxyPort(); /* Set the proxy information. */ client.getHostConfiguration().setProxy(proxyHost, proxyPort); /* Get the credentials. */ final String user = proxy.getUser(); final String password = proxy.getPassword(); /* Set them, if the credentials are complete. */ if (user != null && password != null) { final Credentials credentials = new UsernamePasswordCredentials(user, password); client.getState().setProxyCredentials(AuthScope.ANY, credentials); } } return client; }
From source file:org.kalypso.commons.net.ProxyUtilities.java
/** * Creates a configured http client. The configuration includes setting of proxy settings. * <p>//from w ww. java 2 s . c o m * IMPORTANT: To use proxy-authentication, you must use the setDoAuthentication Method of the HttpMethod you are going * to use. * </p> * <strong>Example:</strong> * * <pre> * HttpMethod method = new GetMethod( m_url.toString() ); * method.setDoAuthentication( true ); * </pre> * * @param timeout * The socket timeout in milliseconds. * @param url * The url, for which the client is needed. Could be null. * @param retries * The number of retries, the http client is going to make. Set to a value lower then 0 to leave it at the * default value. * @return The configured http client. If no proxy is set or the host, included in the url is a non proxy host, it * will be a normal http client with the given timeout and retries. If url is null, the check for non proxy * hosts is omitted. */ public static HttpClient getConfiguredHttpClient(final int timeout, final URL url, final int retries) { /* Create the new http client. */ final HttpClient client = new HttpClient(); /* Client should always authenticate before making a connection. */ client.getParams().setAuthenticationPreemptive(true); client.getParams().setSoTimeout(timeout); /* If a retry count is given, set the number of retries. */ if (retries >= 0) client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(retries, true)); /* Get the proxy object. */ final Proxy proxy = getProxy(); /* If the proxy should be used, configure the client with it. */ if (proxy.useProxy() && !isNonProxyHost(url)) { /* Get the proxy data. */ final String proxyHost = proxy.getProxyHost(); final int proxyPort = proxy.getProxyPort(); /* Set the proxy information. */ client.getHostConfiguration().setProxy(proxyHost, proxyPort); /* Get the credentials. */ final String user = proxy.getUser(); final String password = proxy.getPassword(); /* Set them, if the credentials are complete. */ if (user != null && password != null) { final Credentials credentials = new UsernamePasswordCredentials(user, password); client.getState().setProxyCredentials(AuthScope.ANY, credentials); } } return client; }
From source file:org.krakenapps.pkg.HttpWagon.java
public static InputStream openDownloadStream(URL url, boolean useAuth, String username, String password) throws IOException { Logger logger = LoggerFactory.getLogger(HttpWagon.class.getName()); logger.trace("http wagon: downloading {}", url); HttpClient client = new HttpClient(); if (useAuth) { client.getParams().setAuthenticationPreemptive(true); Credentials defaultcreds = new UsernamePasswordCredentials(username, password); client.getState().setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM), defaultcreds);//www .j a v a2 s.c o m } HttpMethod method = new GetMethod(url.toString()); int socketTimeout = getSocketTimeout(); int connectionTimeout = getConnectTimeout(); client.getParams().setParameter("http.socket.timeout", socketTimeout); client.getParams().setParameter("http.connection.timeout", connectionTimeout); client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, null); int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new IOException("method failed: " + method.getStatusLine()); } return method.getResponseBodyAsStream(); }
From source file:org.kuali.mobility.athletics.service.AthleticsServiceImpl.java
private InputStream getInputStreamFromGetMethod(GetMethod get) throws Exception { get.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false)); HttpClient httpClient = new HttpClient(); httpClient.getParams().setParameter(HttpClientParams.SO_TIMEOUT, new Integer(socketTimeout)); httpClient.getParams().setParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT, new Long(connectionManagerTimeout)); httpClient.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, new Integer(connectionTimeout)); int status = httpClient.executeMethod(get); if (status == HttpStatus.SC_OK) { return get.getResponseBodyAsStream(); }//from ww w. j a va 2 s . co m return null; }
From source file:org.kuali.mobility.knowledgebase.service.KnowledgeBaseServiceImpl.java
private String callKnowledgeBase(String url, RequestEntity requestEntity, boolean isPost) throws Exception { String output = null;/* w w w . j ava 2s . co m*/ // Document doc = null; // SAXBuilder builder = new SAXBuilder(); // BufferedReader in = null; HttpClient client = null; client = new HttpClient(); Credentials defaultcreds = new UsernamePasswordCredentials(this.username, this.password); client.getState().setCredentials(new AuthScope("remote.kb.iu.edu", 80, AuthScope.ANY_REALM), defaultcreds); HttpMethodBase method = null; if (isPost) { method = preparePostMethod(url, requestEntity); } else { method = new GetMethod(url); } method.setDoAuthentication(true); // int timeout = getSocketTimeout(Constants.RSS_SOCKET_TIMEOUT_SECONDS, Constants.RSS_SOCKET_DEFAULT_TIMEOUT); int timeout = getSocketTimeout("blah", 5000); client.getParams().setParameter(HttpClientParams.SO_TIMEOUT, new Integer(timeout)); client.getParams().setParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT, new Long(timeout)); client.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, new Integer(timeout)); try { int status = client.executeMethod(method); // System.out.println(status + "\n" + get.getResponseBodyAsString()); // in = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream())); // doc = builder.build(in); output = this.inputStreamToString(method.getResponseBodyAsStream()); } finally { method.releaseConnection(); } return output; }
From source file:org.kuali.mobility.maps.controllers.MapsController.java
private InputStream getInputStreamFromGetMethod(GetMethod get, int timeout) throws Exception { get.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false)); HttpClient httpClient = new HttpClient(); httpClient.getParams().setParameter(HttpClientParams.SO_TIMEOUT, new Integer(timeout)); httpClient.getParams().setParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT, new Long(timeout)); httpClient.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, new Integer(timeout)); int status = httpClient.executeMethod(get); if (status == HttpStatus.OK.value()) { return get.getResponseBodyAsStream(); }// w w w. j a va 2 s .c o m return null; }
From source file:org.kuali.rice.ksb.messaging.HttpInvokerConnectorConfigurationTest.java
protected void testHttpClientConfigurationImpl(String configType) throws Exception { JavaServiceDefinition javaServiceDefinition = new JavaServiceDefinition(); javaServiceDefinition.setServiceName(new QName("test", "test")); JavaServiceConfiguration configuration = JavaServiceConfiguration .fromServiceDefinition(javaServiceDefinition); // test the default configuration ConfigContext.init(getConfigObject(configType)); HttpInvokerConnector httpConnector = new HttpInvokerConnector(configuration, null); HttpClient httpClient = httpConnector.getHttpClient(); HttpConnectionManager connectionManager = httpClient.getHttpConnectionManager(); assertTrue("Should be a multi-threaded connection manager.", connectionManager instanceof MultiThreadedHttpConnectionManager); int defaultMaxConnectionsPerHost = connectionManager.getParams().getDefaultMaxConnectionsPerHost(); assertEquals(20, defaultMaxConnectionsPerHost); assertEquals(20, connectionManager.getParams().getMaxTotalConnections()); assertEquals(10000, connectionManager.getParams().getConnectionTimeout()); assertEquals(10000, httpClient.getParams().getConnectionManagerTimeout()); assertEquals(CookiePolicy.RFC_2109, httpClient.getParams().getCookiePolicy()); // re-init the core with some of these paramters changed Config config = getConfigObject(configType); config.putProperty("http.connection-manager.max-total", "500"); config.putProperty("http.connection-manager.timeout", "5000"); config.putProperty("http.connection.timeout", "15000"); config.putProperty("http.somerandomproperty", "thisismyproperty"); config.putProperty("http.authentication.preemptive", "false"); ConfigContext.init(config);//from ww w.j ava 2s. com httpConnector = new HttpInvokerConnector(configuration, null); httpClient = httpConnector.getHttpClient(); connectionManager = httpClient.getHttpConnectionManager(); assertTrue("Should be a multi-threaded connection manager.", connectionManager instanceof MultiThreadedHttpConnectionManager); defaultMaxConnectionsPerHost = connectionManager.getParams().getDefaultMaxConnectionsPerHost(); assertEquals(20, defaultMaxConnectionsPerHost); assertEquals(500, connectionManager.getParams().getMaxTotalConnections()); assertEquals(15000, connectionManager.getParams().getConnectionTimeout()); assertEquals(5000, httpClient.getParams().getConnectionManagerTimeout()); assertEquals(CookiePolicy.RFC_2109, httpClient.getParams().getCookiePolicy()); assertFalse(httpClient.getParams().isAuthenticationPreemptive()); // do another one that checks that booleans are working properly config = getConfigObject(configType); config.putProperty("http.authentication.preemptive", "true"); ConfigContext.init(config); httpConnector = new HttpInvokerConnector(configuration, null); httpClient = httpConnector.getHttpClient(); assertTrue(httpClient.getParams().isAuthenticationPreemptive()); // check setting the classname of the connection manager config = getConfigObject(configType); config.putProperty("http.connection-manager.class", MyHttpConnectionManager.class.getName()); ConfigContext.init(config); httpConnector = new HttpInvokerConnector(configuration, null); httpClient = httpConnector.getHttpClient(); connectionManager = httpClient.getHttpConnectionManager(); assertTrue("Should be a MyHttpConnectionManager.", connectionManager instanceof MyHttpConnectionManager); // now try setting the retry handler which expects an object that we can't pipe through our // String-based configuration. This is an illegal parameter to configure and we should // recieve a WorkflowRuntimeException config = getConfigObject(configType); config.putProperty("http.method.retry-handler", "badparm"); ConfigContext.init(config); try { httpConnector = new HttpInvokerConnector(configuration, null); fail("An exception should have been thrown because the retry handler is an illegal parameter."); } catch (Exception e) { //nothing to do here } }
From source file:org.lareferencia.backend.rest.BackEndController.java
@ResponseBody @RequestMapping(value = "/public/harvestMetadataByRecordID/{id}", method = RequestMethod.GET) public String harvestyMetadataByRecordID(@PathVariable Long id) throws Exception { OAIRecord record = recordRepository.findOne(id); String result = ""; if (record != null) { Network network = record.getSnapshot().getNetwork(); ArrayList<OAIOrigin> origins = new ArrayList<>(network.getOrigins()); String oaiURLBase = origins.get(0).getUri(); String recordURL = oaiURLBase + "?verb=GetRecord&metadataPrefix=oai_dc&identifier=" + record.getIdentifier(); HttpClient client = new HttpClient(); client.getParams().setParameter("http.protocol.content-charset", "UTF-8"); HttpMethod method = new GetMethod(recordURL); int responseCode = client.executeMethod(method); if (responseCode != 200) { throw new HttpException( "HttpMethod Returned Status Code: " + responseCode + " when attempting: " + recordURL); }//w ww . j a v a 2 s . co m result = new String(method.getResponseBody(), "UTF-8"); } return result; }
From source file:org.lmn.fc.frameworks.starbase.plugins.observatory.ui.instruments.commands.capture.CaptureImage.java
/*********************************************************************************************** * doCaptureImage()./*from ww w . j a v a2 s. c o m*/ * http://hc.apache.org/httpclient-3.x/tutorial.html * http://www.eboga.org/java/open-source/httpclient-demo.html * * @param dao * @param commandmessage * * @return ResponseMessageInterface */ public static ResponseMessageInterface doCaptureImage(final ObservatoryInstrumentDAOInterface dao, final CommandMessageInterface commandmessage) { final String SOURCE = "CaptureImage.doCaptureImage()"; final CommandType cmdCapture; String strResponseValue; final ResponseMessageInterface responseMessage; // Initialise dao.clearEventLogFragment(); // Get the latest Resources dao.readResources(); // Don't affect the CommandType of the incoming Command cmdCapture = (CommandType) commandmessage.getCommandType().copy(); // Ensure we are dealing with an Ethernet-based instrument if ((commandmessage.getInstrument() != null) && (commandmessage.getInstrument().getController() != null) && (commandmessage.getInstrument().getController().getIPAddress() != null) && (dao.getRemoteDataConnection() != null)) { final HttpClient client; final HttpMethod method; final String strURL; // Set up the HttpClient client = new HttpClient(); client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(1, false)); // Beware filename part (e.g. IMAGE.JPG) *must* be uppercase! // Assume that we are dealing with a valid Ethernet Controller strURL = ControlPanelInterface.PREFIX_HTTP + IPVersion.stripTrailingPaddingFromIPAddressAndPort( commandmessage.getInstrument().getController().getIPAddress()); // The DAO Hostname contains the Value of Property KEY_DAO_IMAGE_FILENAME method = new GetMethod(strURL + "/" + dao.getRemoteDataConnection().getHostname()); // See: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html // The User-Agent request-header field contains information about the user agent originating the request method.setRequestHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)"); // The Referer[sic] request-header field allows the client to specify, for the server's benefit, // the address (URI) of the resource from which the Request-URI was obtained // (the "referrer", although the header field is misspelled.) method.setRequestHeader("Referer", strURL + "/Jview.htm"); SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.INFO, METADATA_TARGET_IMAGE + METADATA_ACTION_CAPTURE + METADATA_ADDRESS + strURL + "/" + dao.getRemoteDataConnection().getHostname() + TERMINATOR, SOURCE, dao.getObservatoryClock()); // Establish the identity of this Instrument using Metadata // from the Framework, Observatory and Observer dao.establishDAOIdentityForCapture(DAOCommandHelper.getCommandCategory(cmdCapture), 0, false, null, null); try { final int intStatus; final InputStream inputStream; // Now try to get the Image intStatus = client.executeMethod(method); // Check the server status if (intStatus != HttpStatus.SC_OK) { SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.WARNING, ObservatoryInstrumentDAOInterface.ERROR_HTTP + method.getStatusLine(), SOURCE, dao.getObservatoryClock()); } // It is vital that the response body is always read, // regardless of the status returned by the server. inputStream = method.getResponseBodyAsStream(); if (inputStream != null) { final BufferedImage image; image = ImageIO.read(inputStream); // If we get here, it must have succeeded... // Pass the Image to the DAO, and then to the Instrument and InstrumentPanel dao.setImageData(image); dao.setUnsavedData(true); inputStream.close(); strResponseValue = ResponseMessageStatus.SUCCESS.getResponseValue(); dao.getResponseMessageStatusList().add(ResponseMessageStatus.SUCCESS); } else { // No data are available SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.WARNING, ObservatoryInstrumentDAOInterface.ERROR_PARSE_DATA, SOURCE, dao.getObservatoryClock()); strResponseValue = ResponseMessageStatus.PREMATURE_TERMINATION.getResponseValue(); dao.getResponseMessageStatusList().add(ResponseMessageStatus.PREMATURE_TERMINATION); } } catch (NumberFormatException exception) { SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.FATAL, ObservatoryInstrumentDAOInterface.ERROR_PARSE_INPUT + exception.getMessage(), SOURCE, dao.getObservatoryClock()); strResponseValue = ResponseMessageStatus.INVALID_PARAMETER.getResponseValue(); dao.getResponseMessageStatusList().add(ResponseMessageStatus.INVALID_PARAMETER); } catch (IllegalArgumentException exception) { SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.FATAL, ObservatoryInstrumentDAOInterface.ERROR_PARSE_INPUT + exception.getMessage(), SOURCE, dao.getObservatoryClock()); strResponseValue = ResponseMessageStatus.INVALID_PARAMETER.getResponseValue(); dao.getResponseMessageStatusList().add(ResponseMessageStatus.INVALID_PARAMETER); } catch (HttpException exception) { SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.WARNING, ObservatoryInstrumentDAOInterface.ERROR_HTTP + exception.getMessage(), SOURCE, dao.getObservatoryClock()); strResponseValue = ResponseMessageStatus.INVALID_MESSAGE.getResponseValue(); dao.getResponseMessageStatusList().add(ResponseMessageStatus.INVALID_MESSAGE); } catch (IOException exception) { SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.WARNING, ObservatoryInstrumentDAOInterface.ERROR_IO + exception.getMessage(), SOURCE, dao.getObservatoryClock()); strResponseValue = ResponseMessageStatus.INVALID_MESSAGE.getResponseValue(); dao.getResponseMessageStatusList().add(ResponseMessageStatus.INVALID_MESSAGE); } finally { // It is important to always release the connection, // regardless of whether the server returned an error or not method.releaseConnection(); } } else { // Incorrectly configured XML strResponseValue = ResponseMessageStatus.INVALID_XML.getResponseValue(); dao.getResponseMessageStatusList().add( DAOCommandHelper.logInvalidXML(dao, SOURCE, METADATA_TARGET_IMAGE, METADATA_ACTION_CAPTURE)); } responseMessage = ResponseMessageHelper.createResponseMessage(dao, commandmessage, cmdCapture, null, null, strResponseValue); return (responseMessage); }