List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestBody
public void setRequestBody(NameValuePair[] paramArrayOfNameValuePair) throws IllegalArgumentException
From source file:org.folg.werelatedata.editor.PageEditor.java
private boolean doPostHttp(String url) { if (!loggedIn) { loggedIn = login();//from w w w .ja v a 2s . c o m } if (!loggedIn) { logger.severe("Not logged in after login attempt"); return false; } PostMethod m = new PostMethod(url); NameValuePair[] nvps = new NameValuePair[variables.size()]; int i = 0; for (String name : variables.keySet()) { String value = variables.get(name); nvps[i] = new NameValuePair(name, value); i++; } m.setRequestBody(nvps); try { client.executeMethod(m); if (m.getStatusCode() == 302) { url = m.getResponseHeader("Location").getValue(); m.releaseConnection(); m = new PostMethod(url); m.setRequestBody(nvps); client.executeMethod(m); } if (m.getStatusCode() != 200) { logger.severe("Unexpected status code on post: " + m.getStatusCode()); return false; } else { contents = getResponse(m); if (contents.contains(NOT_LOGGED_IN)) { loggedIn = false; logger.warning("Not logged in"); return false; } else if (contents.contains(STILL_EDITING)) { logger.warning("Still editing"); return false; } } } catch (IOException e) { logger.warning("IOException on " + url + " -> " + e); return false; } finally { m.releaseConnection(); } return true; }
From source file:org.folg.werelatedata.editor.PageEditor.java
private boolean login() { String url = constructUrl("Special:Userlogin", "submitlogin", "type=login"); logger.info("Logging in: " + url); PostMethod m = new PostMethod(url); NameValuePair[] nvp = { new NameValuePair("wpName", agentUsername), new NameValuePair("wpPassword", agentPassword), new NameValuePair("wpLoginattempt", "Log in") }; m.setRequestBody(nvp); try {//from ww w . j a v a 2 s . c o m client.executeMethod(m); if (m.getStatusCode() == 302) { url = m.getResponseHeader("Location").getValue(); m.releaseConnection(); m = new PostMethod(url); m.setRequestBody(nvp); client.executeMethod(m); } if (m.getStatusCode() != 200) { logger.severe("Unexpected status code logging in: " + m.getStatusCode()); return false; } else { String returnText = getResponse(m); if (returnText.indexOf("Login successful") == -1) { logger.severe("There was a problem logging in. Here is the text:\n\n" + returnText); return false; } } } catch (IOException e) { logger.severe("There was an IOException when executing this url: " + url + " -> " + e); return false; } finally { m.releaseConnection(); } return true; }
From source file:org.gcaldaemon.core.GmailEntry.java
private final void connectLDAP(String username, String password) throws Exception { // Google Apps For Your Domain support String domain = null;// w w w. j av a 2 s .c o m int i = username.indexOf('@'); String loginUsername = username; String loginURL = "https://www.google.com/accounts/ServiceLoginAuth"; if (i != -1) { if (username.indexOf("gmail.com") == -1) { domain = username.substring(i + 1); loginUsername = username.substring(0, i); // Use Google Apps URLs instead of 'gmail.com' URLs gmailURL = "http://mail.google.com/a/" + domain + '/'; loginURL = "https://www.google.com/a/" + domain + "/ServiceLogin"; logoutURL = "http://mail.google.com/a/" + domain + "/?logout"; refererURL = "https://www.google.com/a/" + domain + "/ServiceLogin?service=mail&continue=https%3A%2F%2Fwww.google.com%3A443%2Fa%2F" + domain + "%2FDashboard&passive=true"; oldContactURL = "http://mail.google.com/a/" + domain + "/?ui=1&view=fec"; newContactURL = "http://mail.google.com/a/" + domain + "/mail/contacts/data/export?" + "exportType=ALL&out=GMAIL_CSV"; } } // Default 'gmail.com' login fields PostMethod post = new PostMethod(loginURL); String usernameField = "Email"; String passwordField = "Passwd"; if (domain != null) { // Google Apps For Your Domain login fields usernameField = "userName"; passwordField = "password"; } // Create login request NameValuePair[] data = { new NameValuePair("service", "mail"), new NameValuePair(usernameField, loginUsername), new NameValuePair(passwordField, password), new NameValuePair("null", "Sign in"), new NameValuePair("continue", gmailURL) }; post.addRequestHeader("User-Agent", USER_AGENT); post.addRequestHeader("referer", refererURL); post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded"); post.setRequestBody(data); // Send login form to Gmail int httpStatus = httpClient.executeMethod(post); if (httpStatus == -1) { throw new Exception("Login failed!\r\n" + "Invalid HTTP status code (check username/password)!"); } String response = post.getResponseBodyAsString(); post.releaseConnection(); if (response.toLowerCase().indexOf("errormsg") != -1) { log.warn("Response from Google:\r\n" + response); throw new Exception("Login failed (check username/password)!"); } // Check redirection #1 GetMethod get = null; String newLocationURL; i = response.toLowerCase().indexOf("moved temporarily"); if (i != -1) { i = response.toLowerCase().indexOf("href"); if (i != -1) { int n = response.indexOf('"', i + 7); // Get new URL #1 newLocationURL = response.substring(i + 6, n); get = new GetMethod(newLocationURL); get.addRequestHeader("User-Agent", USER_AGENT); try { httpStatus = httpClient.executeMethod(get); // Get 'GMAIL_AT' cookie's value gmailAt = getGmailAt(get.getRequestHeaders()); response = get.getResponseBodyAsString(); get.releaseConnection(); } catch (IOException e) { log.error("Failed to redirect URL!", e); } } } // Finish login (cookie handshake) get = new GetMethod(gmailURL); get.addRequestHeader("User-Agent", USER_AGENT); get.addRequestHeader("referer", refererURL); get.addRequestHeader("Content-Type", "text/html"); try { httpStatus = httpClient.executeMethod(get); // Get 'GMAIL_AT' cookie's value gmailAt = getGmailAt(get.getRequestHeaders()); // Check redirection #2 if (httpStatus == HttpStatus.SC_MOVED_PERMANENTLY || httpStatus == HttpStatus.SC_MOVED_TEMPORARILY || httpStatus == HttpStatus.SC_SEE_OTHER || httpStatus == HttpStatus.SC_TEMPORARY_REDIRECT) { // Get new URL #2 Header newLocationHeader = get.getResponseHeader("location"); if (newLocationHeader != null) { newLocationURL = newLocationHeader.getValue(); get.releaseConnection(); get = new GetMethod(newLocationURL); try { httpStatus = httpClient.executeMethod(get); // Check redirection #3 if (httpStatus == HttpStatus.SC_MOVED_PERMANENTLY || httpStatus == HttpStatus.SC_MOVED_TEMPORARILY || httpStatus == HttpStatus.SC_SEE_OTHER || httpStatus == HttpStatus.SC_TEMPORARY_REDIRECT) { // Get new URL #3 newLocationHeader = get.getResponseHeader("location"); if (newLocationHeader != null) { newLocationURL = newLocationHeader.getValue(); get.releaseConnection(); get = new GetMethod(newLocationURL); try { httpStatus = httpClient.executeMethod(get); // Get 'GMAIL_AT' cookie's value gmailAt = getGmailAt(get.getRequestHeaders()); get.releaseConnection(); } catch (IOException e) { log.warn("Failed to redirect URL!", e); } } else { log.warn("Missing location URL!"); } } } catch (IOException e) { log.warn("Failed to redirect URL!", e); } } else { log.warn("Missing location header!"); } } } catch (IOException e) { log.error("Failed to open URL", e); } }
From source file:org.gcaldaemon.core.GmailEntry.java
public final String downloadCSV() throws Exception { // Use the new download URL GetMethod get = null;/* ww w . jav a2s .co m*/ try { get = new GetMethod(newContactURL); get.addRequestHeader("User-Agent", USER_AGENT); get.addRequestHeader("referer", gmailURL); get.addRequestHeader("Content-Type", "text/html"); int status = httpClient.executeMethod(get); String csv = get.getResponseBodyAsString(); if (status == 200 && csv.toLowerCase().indexOf("<html") == -1) { return csv; } } finally { if (get != null) { try { get.releaseConnection(); } catch (Exception ignored) { } } } // Use the deprecated download URL PostMethod post = null; try { post = new PostMethod(oldContactURL); post.addRequestHeader("User-Agent", USER_AGENT); post.addRequestHeader("referer", gmailURL); post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded"); NameValuePair[] data2 = { new NameValuePair("at", gmailAt), new NameValuePair("ecf", "g"), new NameValuePair("ac", "Export Contacts") }; post.setRequestBody(data2); int status = httpClient.executeMethod(post); String csv = post.getResponseBodyAsString(); if (status == 200 && csv.toLowerCase().indexOf("<html") == -1) { return csv; } } finally { if (post != null) { try { post.releaseConnection(); } catch (Exception ignored) { } } } log.warn("Incompatible Gmail interface -" + " unable to download contacts!"); return null; }
From source file:org.globus.axis.transport.commons.tests.CommonsHttpConnectionManagerTest.java
public void testHTTPContinue() throws Exception { HostConfiguration config = new HostConfiguration(); config.setHost(address, server1.getLocalPort()); HttpClient httpClient = new HttpClient(); PostMethod method = new PostMethod("/foo/bar"); method.setRequestBody("helloworld\r\n\r\n"); int returnCode = httpClient.executeMethod(config, method, null); assertEquals(200, returnCode);/*from ww w. ja va 2s .c o m*/ }
From source file:org.gluu.oxtrust.action.TestScimOperationAction.java
private HttpClient createFormBasedHttpClient(String userId, String password, String base) { HttpClient httpClient = new HttpClient(); httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); GetMethod loginGetMethod = new GetMethod(base + "/login.htm"); try {/*from w w w .j a v a 2s . c o m*/ httpClient.executeMethod(loginGetMethod); } catch (Exception ex) { log.error("Failed to load login form", ex); } finally { loginGetMethod.releaseConnection(); } if (loginGetMethod.getStatusLine().getStatusCode() != Response.Status.OK.getStatusCode()) { log.error("Failed to load login form"); return null; } PostMethod logingPostMethod = new PostMethod(base + "/login.htm"); // Prepare login parameters NameValuePair viewState = new NameValuePair("javax.faces.ViewState", "j_id1"); NameValuePair action = new NameValuePair("loginForm:submit", "Login"); NameValuePair form = new NameValuePair("loginForm", "loginForm"); NameValuePair userid = new NameValuePair("loginForm:username", userId); NameValuePair userPassword = new NameValuePair("loginForm:password", password); logingPostMethod.setRequestBody(new NameValuePair[] { viewState, action, form, userid, userPassword }); try { httpClient.executeMethod(logingPostMethod); } catch (Exception ex) { log.error("Failed to login", ex); } finally { logingPostMethod.releaseConnection(); } if (logingPostMethod.getStatusLine().getStatusCode() != 302) { log.error("Failed to login"); return null; } return httpClient; }
From source file:org.iavante.sling.commons.services.CopyAndRenameOperationIT.java
protected void setUp() { Map<String, String> envs = System.getenv(); Set<String> keys = envs.keySet(); Iterator<String> it = keys.iterator(); boolean hashost = false; while (it.hasNext()) { String key = (String) it.next(); if (key.compareTo(HOSTVAR) == 0) { SLING_URL = SLING_URL + (String) envs.get(key); hashost = true;/*from w w w . java 2s.co m*/ } } if (hashost == false) SLING_URL = SLING_URL + HOSTPREDEF; client = new HttpClient(); title_col = "Title collection"; title1 = "Test case content 1"; title2 = "Test case content 2"; source_file = "test.avi"; source_mime = "video/avi"; source_dest_slug = "fuente_default"; source_dest_title = "Fuente por defecto"; description1 = "Description 1"; description2 = "Description 2"; schema = "default"; slug_collection = "admin"; slug_content1 = "it_content_1"; slug_content2 = "it_content_2"; authPrefs.add(AuthPolicy.DIGEST); authPrefs.add(AuthPolicy.BASIC); defaultcreds = new UsernamePasswordCredentials("admin", "admin"); client.getParams().setAuthenticationPreemptive(true); client.getState().setCredentials(AuthScope.ANY, defaultcreds); client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); // Create collection PostMethod post_create_col = new PostMethod(SLING_URL + COLLECTIONS_URL + slug_collection); post_create_col.setDoAuthentication(true); NameValuePair[] data_create_col = { new NameValuePair("sling:resourceType", "gad/collection"), new NameValuePair("title", title_col), new NameValuePair("subtitle", ""), new NameValuePair("schema", schema), new NameValuePair("jcr:created", ""), new NameValuePair("jcr:createdBy", ""), new NameValuePair("jcr:lastModified", ""), new NameValuePair("jcr:lastModifiedBy", "") }; post_create_col.setRequestBody(data_create_col); try { client.executeMethod(post_create_col); } catch (HttpException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } post_create_col.releaseConnection(); // Create content in collection try { Thread.sleep(2000); } catch (InterruptedException e1) { e1.printStackTrace(); } PostMethod post_create = new PostMethod( SLING_URL + COLLECTIONS_URL + slug_collection + "/" + CONTENTS_FOLDER + "/" + slug_content1); post_create.setDoAuthentication(true); NameValuePair[] data_create = { new NameValuePair("sling:resourceType", "gad/content"), new NameValuePair("title", title1), new NameValuePair("schema", schema), new NameValuePair("description", description1), new NameValuePair("author", "Test case"), new NameValuePair("origin", "Test case"), new NameValuePair("lang", "es"), new NameValuePair("tags@TypeHint", "String[]"), new NameValuePair("state", "pending"), new NameValuePair("jcr:created", ""), new NameValuePair("jcr:createdBy", ""), new NameValuePair("jcr:lastModified", ""), new NameValuePair("jcr:lastModifiedBy", ""), new NameValuePair("_charset_", "utf-8") }; post_create.setRequestBody(data_create); try { client.executeMethod(post_create); } catch (HttpException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } post_create.releaseConnection(); try { Thread.sleep(2000); } catch (InterruptedException e1) { e1.printStackTrace(); } // Create the source PostMethod post_create_source = new PostMethod( SLING_URL + COLLECTIONS_URL + slug_collection + "/" + SOURCES_FOLDER + "/" + source_title); post_create.setDoAuthentication(true); NameValuePair[] data_create_source = { new NameValuePair("sling:resourceType", "gad/source"), new NameValuePair("title", source_dest_title), new NameValuePair("file", source_file), new NameValuePair("mimetype", source_mime), new NameValuePair("text_encoding", ""), new NameValuePair("lang", ""), new NameValuePair("length", ""), new NameValuePair("size", ""), new NameValuePair("type", ""), new NameValuePair("bitrate", ""), new NameValuePair("tracks_number", ""), new NameValuePair("track_1_type", ""), new NameValuePair("track_1_encoding", ""), new NameValuePair("track_1_features", ""), new NameValuePair("track_2_type", ""), new NameValuePair("track_2_encoding", ""), new NameValuePair("track_2_features", ""), new NameValuePair("jcr:created", ""), new NameValuePair("jcr:createdBy", ""), new NameValuePair("jcr:lastModified", ""), new NameValuePair("jcr:lastModifiedBy", "") }; post_create_source.setRequestBody(data_create_source); try { client.executeMethod(post_create_source); } catch (HttpException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } assertEquals(201, post_create_source.getStatusCode()); post_create_source.releaseConnection(); }
From source file:org.iavante.sling.commons.services.CopyAndRenameOperationIT.java
protected void tearDown() { // Delete the content try {/*from w w w .j a va 2 s.co m*/ Thread.sleep(6000); } catch (InterruptedException e1) { e1.printStackTrace(); } PostMethod post_delete = new PostMethod(SLING_URL + COLLECTIONS_URL + slug_collection); NameValuePair[] data_delete = { new NameValuePair(":operation", "delete"), }; post_delete.setDoAuthentication(true); post_delete.setRequestBody(data_delete); try { client.executeMethod(post_delete); } catch (HttpException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } post_delete.releaseConnection(); }
From source file:org.iavante.sling.commons.services.CopyAndRenameOperationIT.java
public void test_copy_and_rename() { try {//from w ww .j a va 2 s . co m Thread.sleep(2000); } catch (InterruptedException e1) { e1.printStackTrace(); } PostMethod post_copyandrename = new PostMethod( SLING_URL + COLLECTIONS_URL + slug_collection + "/" + SOURCES_FOLDER + "/" + source_title); post_copyandrename.setDoAuthentication(true); String dest = COLLECTIONS_URL + slug_collection + "/" + CONTENTS_FOLDER + "/" + slug_content1 + "/" + SOURCES_FOLDER + "/" + source_dest_slug; NameValuePair[] data_copy = { new NameValuePair(":operation", "copyandrename"), new NameValuePair(":dest", dest) }; post_copyandrename.setRequestBody(data_copy); try { client.executeMethod(post_copyandrename); } catch (HttpException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } post_copyandrename.releaseConnection(); // Create another content in collection try { Thread.sleep(4000); } catch (InterruptedException e1) { e1.printStackTrace(); } HttpMethod get_content = new GetMethod(SLING_URL + dest + "/file"); try { this.client.executeMethod(get_content); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // handle response. String response_body = ""; try { response_body = get_content.getResponseBodyAsString(); } catch (IOException e) { e.printStackTrace(); } assertEquals(response_body, source_file); get_content.releaseConnection(); HttpMethod get_content_title = new GetMethod(SLING_URL + dest + "/title"); try { this.client.executeMethod(get_content_title); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // handle response. response_body = ""; try { response_body = get_content_title.getResponseBodyAsString(); } catch (IOException e) { e.printStackTrace(); } assertEquals(response_body, source_dest_title); get_content.releaseConnection(); // Bad operation PostMethod post_copyandrename_bad = new PostMethod( SLING_URL + COLLECTIONS_URL + slug_collection + "/" + SOURCES_FOLDER); dest = COLLECTIONS_URL + slug_collection + "/" + CONTENTS_FOLDER + "/" + slug_content1 + "/" + SOURCES_FOLDER + "/" + source_dest_slug; NameValuePair[] data_copy_bad = { new NameValuePair(":operation", "copyandrename"), new NameValuePair(":dest", dest) }; post_copyandrename_bad.setRequestBody(data_copy_bad); try { client.executeMethod(post_copyandrename_bad); } catch (HttpException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } assertEquals(post_copyandrename_bad.getStatusCode(), 412); post_copyandrename_bad.releaseConnection(); }
From source file:org.iavante.sling.commons.services.DistributionServerTestIT.java
private void createContent() { PostMethod post_create_ok = new PostMethod(SLING_URL + CATALOG_URL + slug); post_create_ok.setDoAuthentication(true); NameValuePair[] data_create_ok = { new NameValuePair("sling:resourceType", "gad/test3"), new NameValuePair("title", this.title), new NameValuePair("schema", this.schema), new NameValuePair("description", "Content description generated by test case. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur."), new NameValuePair("jcr:createdBy", ""), new NameValuePair("jcr:lastModifiedBy", "") }; post_create_ok.setRequestBody(data_create_ok); post_create_ok.setDoAuthentication(true); try {/*from ww w . ja va 2 s .c o m*/ client.executeMethod(post_create_ok); } catch (HttpException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } // Content created System.out.println("Created ok: " + post_create_ok.getStatusCode()); assertEquals(201, post_create_ok.getStatusCode()); post_create_ok.releaseConnection(); }