List of usage examples for org.apache.commons.httpclient HttpClient HttpClient
public HttpClient()
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 v a 2 s . c om 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:PostXML.java
/** * * Usage:/* www. ja v a 2s. co m*/ * java PostXML http://mywebserver:80/ c:\foo.xml * * @param args command line arguments * Argument 0 is a URL to a web server * Argument 1 is a local filename * */ public static void main(String[] args) throws Exception { if (args.length != 2) { System.out.println( "Usage: java -classpath <classpath> [-Dorg.apache.commons.logging.simplelog.defaultlog=<loglevel>] PostXML <url> <filename>]"); System.out.println("<classpath> - must contain the commons-httpclient.jar and commons-logging.jar"); System.out.println("<loglevel> - one of error, warn, info, debug, trace"); System.out.println("<url> - the URL to post the file to"); System.out.println("<filename> - file to post to the URL"); System.out.println(); System.exit(1); } // Get target URL String strURL = args[0]; // Get file to be posted String strXMLFilename = args[1]; File input = new File(strXMLFilename); // Prepare HTTP post PostMethod post = new PostMethod(strURL); // Request content will be retrieved directly // from the input stream RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1"); post.setRequestEntity(entity); // Get HTTP client HttpClient httpclient = new HttpClient(); // Execute request try { int result = httpclient.executeMethod(post); // Display status code System.out.println("Response status code: " + result); // Display response System.out.println("Response body: "); System.out.println(post.getResponseBodyAsString()); } finally { // Release current connection to the connection pool once you are done post.releaseConnection(); } }
From source file:kevin.gvmsgarch.App.java
public static void main(String[] args) throws HttpException, IOException, ParserConfigurationException, SAXException, XPathExpressionException, JSONException, InterruptedException { System.out.println("Google Voice Message Archiver"); System.out.println("Copyright (C) 2013 Kevin Carter"); System.out.println("This program comes with ABSOLUTELY NO WARRANTY"); System.out.println("This is free software, and you are welcome to redistribute it"); System.out.println("under certain conditions. See the LICENSE file or"); System.out.println("http://www.gnu.org/licenses/gpl-3.0.txt for details"); try {/* ww w. j a v a 2s. c om*/ HttpClient c = new HttpClient(); String userName = getUserName(); String password = getPassword(); int locationChosenIndex = JOptionPane.CLOSED_OPTION; if (password != null) { locationChosenIndex = JOptionPane.showOptionDialog(null, "Message source", "", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, Worker.ListLocation.values(), Worker.ListLocation.inbox); } if (locationChosenIndex != JOptionPane.CLOSED_OPTION) { int modeChosenIndex = 0; Worker.ArchiveMode modeChosen = null; Worker.ListLocation location = Worker.ListLocation.values()[locationChosenIndex]; Worker.ArchiveMode[] availableModes = location.getAllowedModes(); if (availableModes.length == 1) { modeChosen = availableModes[0]; } else { modeChosenIndex = JOptionPane.showOptionDialog(null, "Operation mode", "", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, availableModes, Worker.ArchiveMode.archive); if (modeChosenIndex != JOptionPane.CLOSED_OPTION) { modeChosen = availableModes[modeChosenIndex]; } } ContactFilter filter = null; if (modeChosenIndex != JOptionPane.CLOSED_OPTION && locationChosenIndex != JOptionPane.CLOSED_OPTION) { filter = buildFilter(); } if (modeChosenIndex != JOptionPane.CLOSED_OPTION && locationChosenIndex != JOptionPane.CLOSED_OPTION && filter != null && areYouSure(modeChosen, location, filter)) { assert modeChosen != null : "ZOMG"; String authToken = getToken(userName, password); String rnrse = getRnrse(authToken); final ProgressMonitor pm = new ProgressMonitor(null, "Working", "", 0, App.parseMsgsLeft(extractInboxJson(authToken, location, 1))); pm.setMillisToDecideToPopup(0); pm.setMillisToPopup(0); Worker worker = new Worker(authToken, rnrse, pm, modeChosen, location, filter); worker.addPropertyChangeListener(new ProgressPropertyChangeListener(pm)); pm.setProgress(0); worker.execute(); } } } catch (Exception ex) { JOptionPane.showMessageDialog(null, ex.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE); } }
From source file:PostSOAP.java
/** * * Usage://from ww w .j ava 2s .c o m * java PostSOAP http://mywebserver:80/ SOAPAction c:\foo.xml * * @param args command line arguments * Argument 0 is a URL to a web server * Argument 1 is the SOAP Action * Argument 2 is a local filename * */ public static void main(String[] args) throws Exception { if (args.length != 3) { System.out.println( "Usage: java -classpath <classpath> [-Dorg.apache.commons.logging.simplelog.defaultlog=<loglevel>] PostSOAP <url> <soapaction> <filename>]"); System.out.println("<classpath> - must contain the commons-httpclient.jar and commons-logging.jar"); System.out.println("<loglevel> - one of error, warn, info, debug, trace"); System.out.println("<url> - the URL to post the file to"); System.out.println("<soapaction> - the SOAP action header value"); System.out.println("<filename> - file to post to the URL"); System.out.println(); System.exit(1); } // Get target URL String strURL = args[0]; // Get SOAP action String strSoapAction = args[1]; // Get file to be posted String strXMLFilename = args[2]; File input = new File(strXMLFilename); // Prepare HTTP post PostMethod post = new PostMethod(strURL); // Request content will be retrieved directly // from the input stream RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1"); post.setRequestEntity(entity); // consult documentation for your web service post.setRequestHeader("SOAPAction", strSoapAction); // Get HTTP client HttpClient httpclient = new HttpClient(); // Execute request try { int result = httpclient.executeMethod(post); // Display status code System.out.println("Response status code: " + result); // Display response System.out.println("Response body: "); System.out.println(post.getResponseBodyAsString()); } finally { // Release current connection to the connection pool once you are done post.releaseConnection(); } }
From source file:ExampleP2PHttpClient.java
public static void main(String[] args) { // initialize JXTA try {//from www . j a v a 2 s .c om // sign in and initialize the JXTA network; profile this peer and create it // if it doesn't exist P2PNetwork.signin("clientpeer", "clientpeerpassword", "TestNetwork", true); } catch (Exception e) { e.printStackTrace(); System.exit(1); } // register the P2P socket protocol factory Protocol jxtaHttp = new Protocol("p2phttp", new P2PProtocolSocketFactory(), 80); Protocol.registerProtocol("p2phttp", jxtaHttp); //create a singular HttpClient object HttpClient client = new HttpClient(); //establish a connection within 50 seconds client.setConnectionTimeout(50000); String url = System.getProperty("url"); if (url == null || url.equals("")) { System.out.println("You must provide a URL to access. For example:"); System.out.println("ant example-webclient-run -D--url=p2phttp://www.somedomain.foo"); System.exit(1); } System.out.println("Connecting to " + url + "..."); HttpMethod method = null; //create a method object method = new GetMethod(url); method.setFollowRedirects(true); method.setStrictMode(false); //} catch (MalformedURLException murle) { // System.out.println("<url> argument '" + url // + "' is not a valid URL"); // System.exit(-2); //} //execute the method String responseBody = null; try { client.executeMethod(method); responseBody = method.getResponseBodyAsString(); } catch (HttpException he) { System.err.println("Http error connecting to '" + url + "'"); System.err.println(he.getMessage()); System.exit(-4); } catch (IOException ioe) { System.err.println("Unable to connect to '" + url + "'"); System.exit(-3); } //write out the request headers System.out.println("*** Request ***"); System.out.println("Request Path: " + method.getPath()); System.out.println("Request Query: " + method.getQueryString()); Header[] requestHeaders = method.getRequestHeaders(); for (int i = 0; i < requestHeaders.length; i++) { System.out.print(requestHeaders[i]); } //write out the response headers System.out.println("*** Response ***"); System.out.println("Status Line: " + method.getStatusLine()); Header[] responseHeaders = method.getResponseHeaders(); for (int i = 0; i < responseHeaders.length; i++) { System.out.print(responseHeaders[i]); } //write out the response body System.out.println("*** Response Body ***"); System.out.println(responseBody); //clean up the connection resources method.releaseConnection(); method.recycle(); System.exit(0); }
From source file:com.ikanow.infinit.e.harvest.enrichment.legacy.HttpClientPost.java
public static void main(String[] args) { verifyArgs(args);//from w w w . j a v a2 s. co m HttpClientPost httpClientPost = new HttpClientPost(); httpClientPost.input = new File(args[0]); httpClientPost.output = new File(args[1]); httpClientPost.client = new HttpClient(); httpClientPost.client.getParams().setParameter("http.useragent", "Calais Rest Client"); httpClientPost.run(); }
From source file:com.cloud.test.utils.TestClient.java
public static void main(String[] args) { String host = "http://localhost"; String port = "8080"; String testUrl = "/client/test"; int numThreads = 1; try {/*from w ww . j a va2s. c o m*/ // Parameters List<String> argsList = Arrays.asList(args); Iterator<String> iter = argsList.iterator(); while (iter.hasNext()) { String arg = iter.next(); // host if (arg.equals("-h")) { host = "http://" + iter.next(); } if (arg.equals("-p")) { port = iter.next(); } if (arg.equals("-t")) { numThreads = Integer.parseInt(iter.next()); } if (arg.equals("-s")) { sleepTime = Long.parseLong(iter.next()); } if (arg.equals("-c")) { cleanUp = Boolean.parseBoolean(iter.next()); if (!cleanUp) sleepTime = 0L; // no need to wait if we don't ever cleanup } if (arg.equals("-r")) { repeat = Boolean.parseBoolean(iter.next()); } if (arg.equals("-u")) { numOfUsers = Integer.parseInt(iter.next()); } if (arg.equals("-i")) { internet = Boolean.parseBoolean(iter.next()); } } final String server = host + ":" + port + testUrl; s_logger.info("Starting test against server: " + server + " with " + numThreads + " thread(s)"); if (cleanUp) s_logger.info("Clean up is enabled, each test will wait " + sleepTime + " ms before cleaning up"); if (numOfUsers > 0) { s_logger.info("Pre-generating users for test of size : " + numOfUsers); users = new String[numOfUsers]; Random ran = new Random(); for (int i = 0; i < numOfUsers; i++) { users[i] = Math.abs(ran.nextInt()) + "-user"; } } for (int i = 0; i < numThreads; i++) { new Thread(new Runnable() { public void run() { do { String username = null; try { long now = System.currentTimeMillis(); Random ran = new Random(); if (users != null) { username = users[Math.abs(ran.nextInt()) % numOfUsers]; } else { username = Math.abs(ran.nextInt()) + "-user"; } NDC.push(username); String url = server + "?email=" + username + "&password=" + username + "&command=deploy"; s_logger.info("Launching test for user: " + username + " with url: " + url); HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); int responseCode = client.executeMethod(method); boolean success = false; String reason = null; if (responseCode == 200) { if (internet) { s_logger.info("Deploy successful...waiting 5 minute before SSH tests"); Thread.sleep(300000L); // Wait 60 seconds so the linux VM can boot up. s_logger.info("Begin Linux SSH test"); reason = sshTest(method.getResponseHeader("linuxIP").getValue()); if (reason == null) { s_logger.info("Linux SSH test successful"); s_logger.info("Begin Windows SSH test"); reason = sshWinTest(method.getResponseHeader("windowsIP").getValue()); } } if (reason == null) { if (internet) { s_logger.info("Windows SSH test successful"); } else { s_logger.info("deploy test successful....now cleaning up"); if (cleanUp) { s_logger.info( "Waiting " + sleepTime + " ms before cleaning up vms"); Thread.sleep(sleepTime); } else { success = true; } } if (users == null) { s_logger.info("Sending cleanup command"); url = server + "?email=" + username + "&password=" + username + "&command=cleanup"; } else { s_logger.info("Sending stop DomR / destroy VM command"); url = server + "?email=" + username + "&password=" + username + "&command=stopDomR"; } method = new GetMethod(url); responseCode = client.executeMethod(method); if (responseCode == 200) { success = true; } else { reason = method.getStatusText(); } } else { // Just stop but don't destroy the VMs/Routers s_logger.info("SSH test failed with reason '" + reason + "', stopping VMs"); url = server + "?email=" + username + "&password=" + username + "&command=stop"; responseCode = client.executeMethod(new GetMethod(url)); } } else { // Just stop but don't destroy the VMs/Routers reason = method.getStatusText(); s_logger.info("Deploy test failed with reason '" + reason + "', stopping VMs"); url = server + "?email=" + username + "&password=" + username + "&command=stop"; client.executeMethod(new GetMethod(url)); } if (success) { s_logger.info("***** Completed test for user : " + username + " in " + ((System.currentTimeMillis() - now) / 1000L) + " seconds"); } else { s_logger.info("##### FAILED test for user : " + username + " in " + ((System.currentTimeMillis() - now) / 1000L) + " seconds with reason : " + reason); } } catch (Exception e) { s_logger.warn("Error in thread", e); try { HttpClient client = new HttpClient(); String url = server + "?email=" + username + "&password=" + username + "&command=stop"; client.executeMethod(new GetMethod(url)); } catch (Exception e1) { } } finally { NDC.clear(); } } while (repeat); } }).start(); } } catch (Exception e) { s_logger.error(e); } }
From source file:edu.caltech.ipac.firefly.server.util.multipart.MultiPartPostBuilder.java
public static void main(String[] args) { HttpClient client = new HttpClient(); System.out.println("conn manager= " + client.getHttpConnectionManager().getClass().getName()); System.out.println("def max per host= " + client.getHttpConnectionManager().getParams().getDefaultMaxConnectionsPerHost()); System.out.println("total max = " + client.getHttpConnectionManager().getParams().getMaxTotalConnections()); }
From source file:edu.umd.cs.submit.CommandLineSubmit.java
public static void main(String[] args) { try {//w w w. j av a 2 s . co m Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443); File home = args.length > 0 ? new File(args[0]) : new File("."); Protocol.registerProtocol("easyhttps", easyhttps); File submitFile = new File(home, ".submit"); File submitUserFile = new File(home, ".submitUser"); File submitIgnoreFile = new File(home, ".submitIgnore"); File cvsIgnoreFile = new File(home, ".cvsignore"); if (!submitFile.canRead()) { System.out.println("Must perform submit from a directory containing a \".submit\" file"); System.out.println("No such file found at " + submitFile.getCanonicalPath()); System.exit(1); } Properties p = new Properties(); p.load(new FileInputStream(submitFile)); String submitURL = p.getProperty("submitURL"); if (submitURL == null) { System.out.println(".submit file does not contain a submitURL"); System.exit(1); } String courseName = p.getProperty("courseName"); String courseKey = p.getProperty("courseKey"); String semester = p.getProperty("semester"); String projectNumber = p.getProperty("projectNumber"); String authenticationType = p.getProperty("authentication.type"); String baseURL = p.getProperty("baseURL"); System.out.println("Submitting contents of " + home.getCanonicalPath()); System.out.println(" as project " + projectNumber + " for course " + courseName); FilesToIgnore ignorePatterns = new FilesToIgnore(); addIgnoredPatternsFromFile(cvsIgnoreFile, ignorePatterns); addIgnoredPatternsFromFile(submitIgnoreFile, ignorePatterns); FindAllFiles find = new FindAllFiles(home, ignorePatterns.getPattern()); Collection<File> files = find.getAllFiles(); boolean createdSubmitUser = false; Properties userProps = new Properties(); if (submitUserFile.canRead()) { userProps.load(new FileInputStream(submitUserFile)); } if (userProps.getProperty("cvsAccount") == null && userProps.getProperty("classAccount") == null || userProps.getProperty("oneTimePassword") == null) { System.out.println(); System.out.println( "We need to authenticate you and create a .submitUser file so you can submit your project"); createSubmitUser(submitUserFile, courseKey, projectNumber, authenticationType, baseURL); createdSubmitUser = true; userProps.load(new FileInputStream(submitUserFile)); } MultipartPostMethod filePost = createFilePost(p, find, files, userProps); HttpClient client = new HttpClient(); client.setConnectionTimeout(HTTP_TIMEOUT); int status = client.executeMethod(filePost); System.out.println(filePost.getResponseBodyAsString()); if (status == 500 && !createdSubmitUser) { System.out.println("Let's try reauthenticating you"); System.out.println(); createSubmitUser(submitUserFile, courseKey, projectNumber, authenticationType, baseURL); userProps.load(new FileInputStream(submitUserFile)); filePost = createFilePost(p, find, files, userProps); client = new HttpClient(); client.setConnectionTimeout(HTTP_TIMEOUT); status = client.executeMethod(filePost); System.out.println(filePost.getResponseBodyAsString()); } if (status != HttpStatus.SC_OK) { System.out.println("Status code: " + status); System.exit(1); } System.out.println("Submission accepted"); } catch (Exception e) { System.out.println(); System.out.println("An Error has occured during submission!"); System.out.println(); System.out.println("[DETAILS]"); System.out.println(e.getMessage()); e.printStackTrace(System.out); System.out.println(); } }
From source file:com.cloud.sample.UserCloudAPIExecutor.java
public static void main(String[] args) { // Host//from w ww .j a v a2 s .com String host = null; // Fully qualified URL with http(s)://host:port String apiUrl = null; // ApiKey and secretKey as given by your CloudStack vendor String apiKey = null; String secretKey = null; try { Properties prop = new Properties(); prop.load(new FileInputStream("usercloud.properties")); // host host = prop.getProperty("host"); if (host == null) { System.out.println( "Please specify a valid host in the format of http(s)://:/client/api in your usercloud.properties file."); } // apiUrl apiUrl = prop.getProperty("apiUrl"); if (apiUrl == null) { System.out.println( "Please specify a valid API URL in the format of command=¶m1=¶m2=... in your usercloud.properties file."); } // apiKey apiKey = prop.getProperty("apiKey"); if (apiKey == null) { System.out.println( "Please specify your API Key as provided by your CloudStack vendor in your usercloud.properties file."); } // secretKey secretKey = prop.getProperty("secretKey"); if (secretKey == null) { System.out.println( "Please specify your secret Key as provided by your CloudStack vendor in your usercloud.properties file."); } if (apiUrl == null || apiKey == null || secretKey == null) { return; } System.out.println("Constructing API call to host = '" + host + "' with API command = '" + apiUrl + "' using apiKey = '" + apiKey + "' and secretKey = '" + secretKey + "'"); // Step 1: Make sure your APIKey is URL encoded String encodedApiKey = URLEncoder.encode(apiKey, "UTF-8"); // Step 2: URL encode each parameter value, then sort the parameters and apiKey in // alphabetical order, and then toLowerCase all the parameters, parameter values and apiKey. // Please note that if any parameters with a '&' as a value will cause this test client to fail since we are using // '&' to delimit // the string List<String> sortedParams = new ArrayList<String>(); sortedParams.add("apikey=" + encodedApiKey.toLowerCase()); StringTokenizer st = new StringTokenizer(apiUrl, "&"); String url = null; boolean first = true; while (st.hasMoreTokens()) { String paramValue = st.nextToken(); String param = paramValue.substring(0, paramValue.indexOf("=")); String value = URLEncoder .encode(paramValue.substring(paramValue.indexOf("=") + 1, paramValue.length()), "UTF-8"); if (first) { url = param + "=" + value; first = false; } else { url = url + "&" + param + "=" + value; } sortedParams.add(param.toLowerCase() + "=" + value.toLowerCase()); } Collections.sort(sortedParams); System.out.println("Sorted Parameters: " + sortedParams); // Step 3: Construct the sorted URL and sign and URL encode the sorted URL with your secret key String sortedUrl = null; first = true; for (String param : sortedParams) { if (first) { sortedUrl = param; first = false; } else { sortedUrl = sortedUrl + "&" + param; } } System.out.println("sorted URL : " + sortedUrl); String encodedSignature = signRequest(sortedUrl, secretKey); // Step 4: Construct the final URL we want to send to the CloudStack Management Server // Final result should look like: // http(s)://://client/api?&apiKey=&signature= String finalUrl = host + "?" + url + "&apiKey=" + apiKey + "&signature=" + encodedSignature; System.out.println("final URL : " + finalUrl); // Step 5: Perform a HTTP GET on this URL to execute the command HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(finalUrl); int responseCode = client.executeMethod(method); if (responseCode == 200) { // SUCCESS! System.out.println("Successfully executed command"); } else { // FAILED! System.out.println("Unable to execute command with response code: " + responseCode); } } catch (Throwable t) { System.out.println(t); } }