List of usage examples for org.apache.commons.httpclient HttpClient getParams
public HttpClientParams getParams()
From source file:com.mytutorials.httpclient.FormLoginDemo.java
public static void main(String[] args) throws Exception { HttpClient client = new HttpClient(); client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT, "http"); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); // 'developer.java.sun.com' has cookie compliance problems // Their session cookie's domain attribute is in violation of the // RFC2109//from ww w.jav a2 s . com // We have to resort to using compatibility cookie policy GetMethod authget = new GetMethod("/servlet/SessionServlet"); client.executeMethod(authget); System.out.println("Login form get: " + authget.getStatusLine().toString()); // release any connection resources used by the method authget.releaseConnection(); // See if we got any cookies CookieSpec cookiespec = CookiePolicy.getDefaultSpec(); Cookie[] initcookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies()); System.out.println("Initial set of cookies:"); if (initcookies.length == 0) { System.out.println("None"); } else { for (int i = 0; i < initcookies.length; i++) { System.out.println("- " + initcookies[i].toString()); } } PostMethod authpost = new PostMethod("/servlet/SessionServlet"); // Prepare login parameters NameValuePair action = new NameValuePair("action", "login"); NameValuePair url = new NameValuePair("url", "/index.html"); NameValuePair userid = new NameValuePair("UserId", "userid"); NameValuePair password = new NameValuePair("Password", "password"); authpost.setRequestBody(new NameValuePair[] { action, url, userid, password }); client.executeMethod(authpost); System.out.println("Login form post: " + authpost.getStatusLine().toString()); // release any connection resources used by the method authpost.releaseConnection(); // See if we got any cookies // The only way of telling whether logon succeeded is // by finding a session cookie Cookie[] logoncookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies()); System.out.println("Logon cookies:"); if (logoncookies.length == 0) { System.out.println("None"); } else { for (int i = 0; i < logoncookies.length; i++) { System.out.println("- " + logoncookies[i].toString()); } } // Usually a successful form-based login results in a redicrect to // another url int statuscode = authpost.getStatusCode(); if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) { Header header = authpost.getResponseHeader("location"); if (header != null) { String newuri = header.getValue(); if ((newuri == null) || (newuri.equals(""))) { newuri = "/"; } System.out.println("Redirect target: " + newuri); GetMethod redirect = new GetMethod(newuri); client.executeMethod(redirect); System.out.println("Redirect: " + redirect.getStatusLine().toString()); // release any connection resources used by the method redirect.releaseConnection(); } else { System.out.println("Invalid redirect"); System.exit(1); } } }
From source file:com.djimenez.tuenti.example.FormLoginDemo.java
public static void main(final String[] args) throws Exception { final HttpClient client = new HttpClient(); client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT, "http"); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); // 'developer.java.sun.com' has cookie compliance problems // Their session cookie's domain attribute is in violation of the RFC2109 // We have to resort to using compatibility cookie policy final GetMethod authget = new GetMethod(LOGON_PATH); authget.setFollowRedirects(true);/*from w w w.j a va2 s . c o m*/ client.executeMethod(authget); System.out.println("Login form get: " + authget.getStatusLine().toString()); // release any connection resources used by the method authget.releaseConnection(); // See if we got any cookies final CookieSpec cookiespec = CookiePolicy.getDefaultSpec(); final Cookie[] initcookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies()); System.out.println("Initial set of cookies:"); checkCookies(initcookies); final PostMethod authpost = new PostMethod(LOGON_PATH); // Prepare login parameters final NameValuePair action = new NameValuePair("action", "do_login"); final NameValuePair url = new NameValuePair("url", "/?m=Login&func=do_login"); final NameValuePair userid = new NameValuePair("email", "david.jimenez19%40gmail.com"); final NameValuePair password = new NameValuePair("input_password", "linda1"); final NameValuePair timeZone = new NameValuePair("timezone", "1"); final NameValuePair timeStamp = new NameValuePair("timezone", "13034395121"); authpost.setRequestBody(new NameValuePair[] { action, url, userid, password, timeZone, timeStamp }); client.executeMethod(authpost); System.out.println("Login form post: " + authpost.getStatusLine().toString()); // release any connection resources used by the method authpost.releaseConnection(); // See if we got any cookies // The only way of telling whether logon succeeded is // by finding a session cookie final Cookie[] logoncookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies()); System.out.println("Logon cookies:" + logoncookies); checkCookies(logoncookies); manageRequest(client, authpost); }
From source file:CookieDemoApp.java
/** * * Usage://from w ww .j a v 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:AlternateAuthenticationExample.java
public static void main(String[] args) throws Exception { HttpClient client = new HttpClient(); client.getState().setCredentials(new AuthScope("myhost", 80, "myrealm"), new UsernamePasswordCredentials("username", "password")); // Suppose the site supports several authetication schemes: NTLM and Basic // Basic authetication is considered inherently insecure. Hence, NTLM authentication // is used per default // This is to make HttpClient pick the Basic authentication scheme over NTLM & Digest List authPrefs = new ArrayList(3); authPrefs.add(AuthPolicy.BASIC);/*from ww w. j a v a2s.c om*/ authPrefs.add(AuthPolicy.NTLM); authPrefs.add(AuthPolicy.DIGEST); client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); GetMethod httpget = new GetMethod("http://myhost/protected/auth-required.html"); try { int status = client.executeMethod(httpget); // print the status and response System.out.println(httpget.getStatusLine()); System.out.println(httpget.getResponseBodyAsString()); } finally { // release any connection resources used by the method httpget.releaseConnection(); } }
From source file:com.zimbra.common.util.ZimbraHttpConnectionManager.java
public static void main(String[] args) { // dump httpclient package defaults System.out.println(dumpParams("httpclient package defaults", new HttpConnectionManagerParams(), new HttpClientParams())); System.out.println(dumpParams("Internal ZimbraHttpConnectionManager", ZimbraHttpConnectionManager.getInternalHttpConnMgr().getParams().getConnMgrParams(), ZimbraHttpConnectionManager.getInternalHttpConnMgr().getDefaultHttpClient().getParams())); System.out.println(dumpParams("External ZimbraHttpConnectionManager", ZimbraHttpConnectionManager.getExternalHttpConnMgr().getParams().getConnMgrParams(), ZimbraHttpConnectionManager.getExternalHttpConnMgr().getDefaultHttpClient().getParams())); HttpClient httpClient = ZimbraHttpConnectionManager.getInternalHttpConnMgr().getDefaultHttpClient(); String connMgrName = httpClient.getHttpConnectionManager().getClass().getSimpleName(); long connMgrTimeout = httpClient.getParams().getConnectionManagerTimeout(); System.out.println("HttpConnectionManager for the HttpClient instance is: " + connMgrName); System.out.println("connection manager timeout for the HttpClient instance is: " + connMgrTimeout); }
From source file:dk.statsbiblioteket.doms.licensemodule.integrationtest.HttpClientPoster.java
public static String postJSON(String url, String content) throws Exception { HttpClient client = new HttpClient(); client.getParams().setParameter("http.useragent", "Dokumentleveringweb XML client"); BufferedReader br = null;//from w w w. j a v a 2s .c o m //TODO property PostMethod method = new PostMethod(url); method.addRequestHeader("Content-Type", "application/json;charset=UTF-8"); method.setRequestBody(content); // How to do this a non-deprecated way? try { int httpCode = client.executeMethod(method); br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream())); String readLine; StringBuilder response = new StringBuilder(); while (((readLine = br.readLine()) != null)) { response.append(readLine); } return response.toString(); } catch (Exception e) { throw e; } finally { method.releaseConnection(); if (br != null) try { br.close(); } catch (Exception fe) { fe.printStackTrace(); } } }
From source file:com.predic8.membrane.integration.Http11Test.java
/** * Note that "Read timed out" indicates incorrect server behavior. The * socket timeout is set on the client to avoid fallback mentioned in * RFC2616 section 8.2.3 ("indefinite period"). *//*www . j a v a 2s . c o m*/ public static void initExpect100ContinueWithFastFail(HttpClient client) { client.getParams().setParameter(HttpProtocolParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); client.getParams().setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, true); client.getParams().setParameter("http.method.retry-handler", new HttpMethodRetryHandler() { @Override public boolean retryMethod(HttpMethod arg0, IOException arg1, int arg2) { return false; } }); client.getParams().setParameter("http.socket.timeout", 7000); }
From source file:com.netflix.postreview.ClientFactory.java
public static HttpClient getClient() throws HttpProxySettingsException { HttpClient httpClient = new HttpClient(connectionManager); httpClient.getParams().setConnectionManagerTimeout(connectionManagerTimeout); httpClient.getParams().setSoTimeout(dataTimeout); return httpClient; }
From source file:eu.impact_project.iif.t2.client.Helper.java
/** * Creates an http client that uses basic authentication. The credentials * will be sent preemptively with each request. * /*from w w w .j av a 2 s . com*/ * @param domain * Authentication domain * @param user * User name for basic authentication * @param password * Password for basic authentication * @return Created client object */ public static HttpClient createAuthenticatingClient(String domain, String user, String password) { HttpClient client = new HttpClient(); client.getParams().setAuthenticationPreemptive(true); client.getState().setCredentials(new AuthScope(domain, -1), new UsernamePasswordCredentials(user, password)); return client; }
From source file:fr.cls.atoll.motu.library.misc.cas.HttpClientTutorial.java
public static void test() { HttpClient client = new HttpClient(); client.getParams().setParameter("http.useragent", "Test Client"); client.getParams().setParameter("http.connection.timeout", new Integer(5000)); GetMethod method = new GetMethod(); FileOutputStream fos = null;// www . j a v a2 s. c om try { method.setURI(new URI("http://www.google.com", true)); int returnCode = client.executeMethod(method); if (returnCode != HttpStatus.SC_OK) { System.err.println("Unable to fetch default page, status code: " + returnCode); } System.err.println(method.getResponseBodyAsString()); method.setURI(new URI("http://www.google.com/images/logo.gif", true)); returnCode = client.executeMethod(method); if (returnCode != HttpStatus.SC_OK) { System.err.println("Unable to fetch image, status code: " + returnCode); } byte[] imageData = method.getResponseBody(); fos = new FileOutputStream(new File("google.gif")); fos.write(imageData); HostConfiguration hostConfig = new HostConfiguration(); hostConfig.setHost("www.yahoo.com", null, 80, Protocol.getProtocol("http")); method.setURI(new URI("/", true)); client.executeMethod(hostConfig, method); System.err.println(method.getResponseBodyAsString()); } catch (HttpException he) { System.err.println(he); } catch (IOException ie) { System.err.println(ie); } finally { method.releaseConnection(); if (fos != null) { try { fos.close(); } catch (Exception fe) { } } } }