List of usage examples for org.apache.commons.httpclient.cookie CookiePolicy RFC_2109
String RFC_2109
To view the source code for org.apache.commons.httpclient.cookie CookiePolicy RFC_2109.
Click Source Link
From source file:CookieDemoApp.java
/** * * Usage://from ww w .jav a 2 s .c o m * java CookieDemoApp http://mywebserver:80/ * * @param args command line arguments * Argument 0 is a URL to a web server * * */ public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println("Usage: java CookieDemoApp <url>"); System.err.println("<url> The url of a webpage"); System.exit(1); } // Get target URL String strURL = args[0]; System.out.println("Target URL: " + strURL); // Get initial state object HttpState initialState = new HttpState(); // Initial set of cookies can be retrieved from persistent storage and // re-created, using a persistence mechanism of choice, Cookie mycookie = new Cookie(".foobar.com", "mycookie", "stuff", "/", null, false); // and then added to your HTTP state instance initialState.addCookie(mycookie); // Get HTTP client instance HttpClient httpclient = new HttpClient(); httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(30000); httpclient.setState(initialState); // RFC 2101 cookie management spec is used per default // to parse, validate, format & match cookies httpclient.getParams().setCookiePolicy(CookiePolicy.RFC_2109); // A different cookie management spec can be selected // when desired //httpclient.getParams().setCookiePolicy(CookiePolicy.NETSCAPE); // Netscape Cookie Draft spec is provided for completeness // You would hardly want to use this spec in real life situations //httppclient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); // Compatibility policy is provided in order to mimic cookie // management of popular web browsers that is in some areas // not 100% standards compliant // Get HTTP GET method GetMethod httpget = new GetMethod(strURL); // Execute HTTP GET int result = httpclient.executeMethod(httpget); // Display status code System.out.println("Response status code: " + result); // Get all the cookies Cookie[] cookies = httpclient.getState().getCookies(); // Display the cookies System.out.println("Present cookies: "); for (int i = 0; i < cookies.length; i++) { System.out.println(" - " + cookies[i].toExternalForm()); } // Release current connection to the connection pool once you are done httpget.releaseConnection(); }
From source file:com.ironiacorp.http.impl.httpclient3.HttpJobRunnerHttpClient3.java
private void setupClient() { MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); // connectionManager.// maxConnectionsPerHost // maxTotalConnections httpClient = new HttpClient(connectionManager); // http://jakarta.apache.org/httpcomponents/httpclient-3.x/preference-api.html HttpClientParams params = httpClient.getParams(); params.setParameter("http.protocol.version", HttpVersion.HTTP_1_1); params.setParameter("http.socket.timeout", new Integer(60000)); params.setParameter("http.protocol.content-charset", "UTF-8"); params.setCookiePolicy(CookiePolicy.RFC_2109); }
From source file:colt.nicity.performance.agent.LatentHttpPump.java
private org.apache.commons.httpclient.HttpClient createApacheClient(String host, int port, int maxConnections, int socketTimeoutInMillis) { HttpConnectionManager connectionManager = createConnectionManager(maxConnections); org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient( connectionManager);/* ww w . j a va 2 s . c om*/ client.getParams().setParameter(HttpMethodParams.COOKIE_POLICY, CookiePolicy.RFC_2109); client.getParams().setParameter(HttpMethodParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8"); client.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false); client.getParams().setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, true); client.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, socketTimeoutInMillis > 0 ? socketTimeoutInMillis : 0); client.getParams().setParameter(HttpConnectionParams.SO_TIMEOUT, socketTimeoutInMillis > 0 ? socketTimeoutInMillis : 0); HostConfiguration hostConfiguration = new HostConfiguration(); configureSsl(hostConfiguration, host, port); configureProxy(hostConfiguration); client.setHostConfiguration(hostConfiguration); return client; }
From source file:com.jivesoftware.os.jive.utils.http.client.HttpClientFactoryProvider.java
public HttpClientFactory createHttpClientFactory(final Collection<HttpClientConfiguration> configurations) { return new HttpClientFactory() { @Override/* w w w .ja va 2s . c o m*/ public HttpClient createClient(String host, int port) { ApacheHttpClient31BackedHttpClient httpClient = createApacheClient(); HostConfiguration hostConfiguration = new HostConfiguration(); configureSsl(hostConfiguration, host, port, httpClient); configureProxy(hostConfiguration, httpClient); httpClient.setHostConfiguration(hostConfiguration); configureOAuth(httpClient); return httpClient; } private ApacheHttpClient31BackedHttpClient createApacheClient() { HttpClientConfig httpClientConfig = locateConfig(HttpClientConfig.class, HttpClientConfig.newBuilder().build()); HttpConnectionManager connectionManager = createConnectionManager(httpClientConfig); org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient( connectionManager); client.getParams().setParameter(HttpMethodParams.COOKIE_POLICY, CookiePolicy.RFC_2109); client.getParams().setParameter(HttpMethodParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8"); client.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false); client.getParams().setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, true); client.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, httpClientConfig.getSocketTimeoutInMillis() > 0 ? httpClientConfig.getSocketTimeoutInMillis() : 0); client.getParams().setParameter(HttpConnectionParams.SO_TIMEOUT, httpClientConfig.getSocketTimeoutInMillis() > 0 ? httpClientConfig.getSocketTimeoutInMillis() : 0); return new ApacheHttpClient31BackedHttpClient(client, httpClientConfig.getCopyOfHeadersForEveryRequest()); } @SuppressWarnings("unchecked") private <T> T locateConfig(Class<? extends T> _class, T defaultConfiguration) { for (HttpClientConfiguration configuration : configurations) { if (_class.isInstance(configuration)) { return (T) configuration; } } return defaultConfiguration; } private boolean hasValidProxyUsernameAndPasswordSettings(HttpClientProxyConfig httpClientProxyConfig) { return StringUtils.isNotBlank(httpClientProxyConfig.getProxyUsername()) && StringUtils.isNotBlank(httpClientProxyConfig.getProxyPassword()); } private HttpConnectionManager createConnectionManager(HttpClientConfig config) { MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); if (config.getMaxConnectionsPerHost() > 0) { connectionManager.getParams() .setDefaultMaxConnectionsPerHost(config.getMaxConnectionsPerHost()); } else { connectionManager.getParams().setDefaultMaxConnectionsPerHost(Integer.MAX_VALUE); } if (config.getMaxConnections() > 0) { connectionManager.getParams().setMaxTotalConnections(config.getMaxConnections()); } return connectionManager; } private void configureOAuth(ApacheHttpClient31BackedHttpClient httpClient) { HttpClientOAuthConfig httpClientOAuthConfig = locateConfig(HttpClientOAuthConfig.class, null); if (httpClientOAuthConfig != null) { String serviceName = httpClientOAuthConfig.getServiceName(); HttpClientConsumerKeyAndSecretProvider consumerKeyAndSecretProvider = httpClientOAuthConfig .getConsumerKeyAndSecretProvider(); String consumerKey = consumerKeyAndSecretProvider.getConsumerKey(serviceName); if (StringUtils.isEmpty(consumerKey)) { throw new RuntimeException( "could create oauth client because consumerKey is null or empty for service:" + serviceName); } String consumerSecret = consumerKeyAndSecretProvider.getConsumerSecret(serviceName); if (StringUtils.isEmpty(consumerSecret)) { throw new RuntimeException( "could create oauth client because consumerSecret is null or empty for service:" + serviceName); } httpClient.setConsumerTokens(consumerKey, consumerSecret); } } private void configureProxy(HostConfiguration hostConfiguration, ApacheHttpClient31BackedHttpClient httpClient) { HttpClientProxyConfig httpClientProxyConfig = locateConfig(HttpClientProxyConfig.class, null); if (httpClientProxyConfig != null) { hostConfiguration.setProxy(httpClientProxyConfig.getProxyHost(), httpClientProxyConfig.getProxyPort()); if (hasValidProxyUsernameAndPasswordSettings(httpClientProxyConfig)) { HttpState state = new HttpState(); state.setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(httpClientProxyConfig.getProxyUsername(), httpClientProxyConfig.getProxyPassword())); httpClient.setState(state); } } } private void configureSsl(HostConfiguration hostConfiguration, String host, int port, ApacheHttpClient31BackedHttpClient httpClient) throws IllegalStateException { HttpClientSSLConfig httpClientSSLConfig = locateConfig(HttpClientSSLConfig.class, null); if (httpClientSSLConfig != null) { Protocol sslProtocol; if (httpClientSSLConfig.getCustomSSLSocketFactory() != null) { sslProtocol = new Protocol(HTTPS_PROTOCOL, new CustomSecureProtocolSocketFactory( httpClientSSLConfig.getCustomSSLSocketFactory()), SSL_PORT); } else { sslProtocol = Protocol.getProtocol(HTTPS_PROTOCOL); } hostConfiguration.setHost(host, port, sslProtocol); httpClient.setUsingSSL(); } else { hostConfiguration.setHost(host, port); } } }; }
From source file:com.ideabase.repository.webservice.client.impl.HttpWebServiceControllerImpl.java
/** * {@inheritDoc}/*from w w w . j av a 2 s. co m*/ */ public WebServiceResponse sendServiceRequest(final WebServiceRequest pRequest) { if (LOG.isDebugEnabled()) { LOG.debug("Sending request - " + pRequest); } // build query string final NameValuePair[] parameters = buildParameters(pRequest); // Send request to server final HttpMethod httpMethod = prepareMethod(pRequest.getRequestMethod(), pRequest.getServiceUri(), parameters); // set cookie policy httpMethod.getParams().setCookiePolicy(CookiePolicy.RFC_2109); // set cookies if (mCookies != null) { httpMethod.setRequestHeader(HEADER_COOKIE, mCookies); } if (pRequest.getCookies() != null) { httpMethod.setRequestHeader(HEADER_COOKIE, pRequest.getCookies()); mCookies = pRequest.getCookies(); } // execute method final HttpClient httpClient = new HttpClient(); final WebServiceResponse response; try { final int status = httpClient.executeMethod(httpMethod); // build web sercie response response = new WebServiceResponse(); response.setResponseStatus(status); response.setResponseContent(new String(httpMethod.getResponseBody())); response.setContentType(httpMethod.getResponseHeader(HEADER_CONTENT_TYPE).getValue()); response.setServiceUri(httpMethod.getURI().toString()); // set cookies final Header cookieHeader = httpMethod.getResponseHeader(HEADER_SET_COOKIE); if (cookieHeader != null) { mCookies = cookieHeader.getValue(); } // set cookies to the returning response object. response.setCookies(mCookies); if (LOG.isDebugEnabled()) { LOG.debug("Cookies - " + mCookies); LOG.debug("Response - " + response); } } catch (Exception e) { throw ServiceException.aNew(pRequest, "Failed to send web service request.", e); } finally { httpMethod.releaseConnection(); } return response; }
From source file:edu.cmu.cs.diamond.pathfind.DjangoAnnotationStore.java
public DjangoAnnotationStore(HttpClient httpClient, String uriPrefix) { if (uriPrefix.endsWith("/")) { this.uriPrefix = uriPrefix; } else {/*from w w w. j a va 2 s. co m*/ this.uriPrefix = uriPrefix + "/"; } this.httpClient = httpClient; httpClient.getParams().setCookiePolicy(CookiePolicy.RFC_2109); }
From source file:com.foglyn.core.FoglynCorePlugin.java
private HttpClient createHttpClient(HttpConnectionManager connectionManager) { HttpClient httpClient = new HttpClient(); httpClient.setHttpConnectionManager(connectionManager); httpClient.getParams().setCookiePolicy(CookiePolicy.RFC_2109); String userAgent = USER_AGENT; String version = getBundleVersion(); if (version != null) { userAgent = USER_AGENT + "/" + version; }/*w w w . ja va 2 s. co m*/ WebUtil.configureHttpClient(httpClient, userAgent); return httpClient; }
From source file:net.sf.webissues.core.WebIssuesClientManager.java
protected HttpClient createHttpClient(AbstractWebLocation location) { HttpClient httpClient = new HttpClient(); httpClient.getParams().setAuthenticationPreemptive(true); HttpConnectionManager connectionManager = WebIssuesClientManager.getConnectionManager(); httpClient.setHttpConnectionManager(connectionManager); connectionManager.getParams().setConnectionTimeout(8000); connectionManager.getParams().setSoTimeout(8000); httpClient.getParams().setCookiePolicy(CookiePolicy.RFC_2109); WebUtil.configureHttpClient(httpClient, WebIssuesClientManager.USER_AGENT); httpClient.setHostConfiguration(WebUtil.createHostConfiguration(httpClient, location, null)); return httpClient; }
From source file:edu.du.penrose.systems.fedoraProxy.web.bus.ProxyController.java
public static void setDefaultHeaders(HttpMethod method) { method.setRequestHeader("Accept", "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); method.setRequestHeader("Connection", "keep-alive"); method.setRequestHeader("Accept-Encoding", "gzip,deflate,sdch"); method.setRequestHeader("Accept-Language", "en-US,en;q=0.8"); method.setRequestHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3"); method.setRequestHeader("Cache-Control", "max-age=0"); method.getParams().setCookiePolicy(CookiePolicy.RFC_2109); // response.setCharacterEncoding( "gzip,deflate" ); // response.setHeader( "Accept-Charset", // "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); // response.setHeader( "Accept-Language", "en-us,en;q=0.5" ); }
From source file:fr.cls.atoll.motu.processor.wps.framework.WPSUtils.java
/** * Performs an HTTP-Get request and provides typed access to the response. * /*ww w . j a va2s . co m*/ * @param <T> * @param worker * @param url * @param postBody * @param headers * @return some object from the url * @throws HttpException * @throws IOException * @throws MotuException */ public static <T> T post(Worker<T> worker, String url, InputStream postBody, Map<String, String> headers) throws HttpException, IOException, MotuException { if (LOG.isDebugEnabled()) { LOG.debug("post(Worker<T>, String, InputStream, Map<String,String>) - start"); } ByteArrayOutputStream out = new ByteArrayOutputStream(); try { IOUtils.copy(postBody, out); } finally { IOUtils.closeQuietly(out); } InputStream postBodyCloned = new ByteArrayInputStream(out.toString().getBytes()); MultiThreadedHttpConnectionManager connectionManager = HttpUtil.createConnectionManager(); HttpClientCAS client = new HttpClientCAS(connectionManager); HttpClientParams clientParams = new HttpClientParams(); //clientParams.setParameter("http.protocol.allow-circular-redirects", true); //HttpClientParams.ALLOW_CIRCULAR_REDIRECTS client.setParams(clientParams); PostMethod post = new PostMethod(url); post.getParams().setCookiePolicy(CookiePolicy.RFC_2109); InputStreamRequestEntity inputStreamRequestEntity = new InputStreamRequestEntity(postBody); post.setRequestEntity(inputStreamRequestEntity); for (String key : headers.keySet()) { post.setRequestHeader(key, headers.get(key)); } String query = post.getQueryString(); // Check redirection // DONT USE post.setFollowRedirects(true); see http://hc.apache.org/httpclient-3.x/redirects.html int httpReturnCode = client.executeMethod(post); if (LOG.isDebugEnabled()) { String msg = String.format("Executing the query:\n==> http code: '%d':\n==> url: '%s'\n==> body:\n'%s'", httpReturnCode, url, query); LOG.debug("post(Worker<T>, String, InputStream, Map<String,String>) - end - " + msg); } if (httpReturnCode == 302) { post.releaseConnection(); String redirectLocation = null; Header locationHeader = post.getResponseHeader("location"); if (locationHeader != null) { redirectLocation = locationHeader.getValue(); if (!WPSUtils.isNullOrEmpty(redirectLocation)) { if (LOG.isDebugEnabled()) { String msg = String.format("Query is redirected to url: '%s'", redirectLocation); LOG.debug("post(Worker<T>, String, InputStream, Map<String,String>) - end - " + msg); } post = new PostMethod(url); post.setRequestEntity(new InputStreamRequestEntity(postBodyCloned)); // Recrire un nouveau InputStream for (String key : headers.keySet()) { post.setRequestHeader(key, headers.get(key)); } clientParams.setBooleanParameter(HttpClientCAS.ADD_CAS_TICKET_PARAM, false); httpReturnCode = client.executeMethod(post); clientParams.setBooleanParameter(HttpClientCAS.ADD_CAS_TICKET_PARAM, true); if (LOG.isDebugEnabled()) { String msg = String.format( "Executing the query:\n==> http code: '%d':\n==> url: '%s'\n==> body:\n'%s'", httpReturnCode, url, query); LOG.debug("post(Worker<T>, String, InputStream, Map<String,String>) - end - " + msg); } } } } T returnValue = worker.work(post.getResponseBodyAsStream()); if (httpReturnCode >= 400) { if (LOG.isDebugEnabled()) { LOG.debug("post(Worker<T>, String, InputStream, Map<String,String>) - end"); } String msg = String.format( "Error while executing the query:\n==> http code: '%d':\n==> url: '%s'\n==> body:\n'%s'", httpReturnCode, url, query); throw new MotuException(msg); } if (LOG.isDebugEnabled()) { LOG.debug("post(Worker<T>, String, InputStream, Map<String,String>) - end"); } return returnValue; }