List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestBody
public void setRequestBody(NameValuePair[] paramArrayOfNameValuePair) throws IllegalArgumentException
From source file:org.tranche.logs.LogUtil.java
/** * Helper method to log an exception to the Tranche error log. * @param e//w w w . j a v a2 s .co m * @param description * @param uzf */ public static void logError(Set<Exception> exceptions, String description, UserZipFile uzf) { // skip all errors originating from JUnit for (Exception e : exceptions) { StackTraceElement[] stes = e.getStackTrace(); for (StackTraceElement ste : stes) { if (ste.getClassName().equals("junit.framework.TestCase")) { return; } } } final StringBuffer descriptionBuffer = new StringBuffer(), exceptionBuffer = new StringBuffer(), userBuffer = new StringBuffer(); // Build: messageBuffer if (description != null && !description.trim().equals("")) { descriptionBuffer.append(description); } else { descriptionBuffer.append(""); } // Build: exceptionBuffer exceptionBuffer.append("Exceptions: " + exceptions.size() + " exceptions to report" + "\n"); for (Exception e : exceptions) { exceptionBuffer.append(e.getClass().getName() + ": " + e.getMessage() + "\n"); for (StackTraceElement ste : e.getStackTrace()) { exceptionBuffer.append(" " + ste + "\n"); } exceptionBuffer.append("\n"); } exceptionBuffer.append("\n"); // Build: userBuffer if (uzf == null) { userBuffer.append(""); } else { userBuffer.append(uzf.getUserNameFromCert() + " <" + uzf.getEmail() + ">"); } final String serversDump = getServersDump(); final String threadDump = getThreadDump(); final String memoryDump = getEnvironmentDump(); final String submitURL = ConfigureTranche.get(ConfigureTranche.CATEGORY_LOGGING, ConfigureTranche.PROP_LOG_ERROR_URL); if (submitURL != null && !submitURL.trim().equals("")) { Thread t = new Thread("Submit error thread") { @Override public void run() { HttpClient c = new HttpClient(); PostMethod pm = new PostMethod(submitURL); try { List<NameValuePair> pairs = new ArrayList<NameValuePair>(); pairs.add(new NameValuePair("Exception", exceptionBuffer.toString())); pairs.add(new NameValuePair("Servers", serversDump)); pairs.add(new NameValuePair("Threads", threadDump)); pairs.add(new NameValuePair("Memory", memoryDump)); pairs.add(new NameValuePair("UserInfo", userBuffer.toString())); pairs.add(new NameValuePair("UserComment", descriptionBuffer.toString())); // create the pair array NameValuePair[] pairArray = new NameValuePair[pairs.size()]; for (int i = 0; i < pairs.size(); i++) { pairArray[i] = pairs.get(i); } // set the values pm.setRequestBody(pairArray); // execute the method int statusCode = c.executeMethod(pm); // If registrar failed to send email, do so here... if (statusCode < 200 || statusCode >= 300) { throw new Exception("Failed to register, returned HTTP status code: " + statusCode); } } catch (Exception e) { e.printStackTrace(); } finally { pm.releaseConnection(); } } }; t.start(); } // Send all the information to the appropriate email addresses if (ConfigureTranche.getAdminEmailAccounts().length > 0) { File tempFile = null; try { String subject = "[" + ConfigureTranche.get(ConfigureTranche.CATEGORY_GENERAL, ConfigureTranche.PROP_NAME) + "] Error @ " + TextUtil.getFormattedDate(TimeUtil.getTrancheTimestamp()); StringBuffer msg = new StringBuffer(); msg.append("User comments:\n"); msg.append(descriptionBuffer + "\n\n\n"); msg.append("Submitted by: " + userBuffer + "\n\n\n"); msg.append(exceptionBuffer + "\n"); tempFile = getTroubleshootingInformationFile(); try { EmailUtil.sendEmailHttp(subject, ConfigureTranche.getAdminEmailAccounts(), msg.toString(), tempFile); } catch (Exception ee) { ee.printStackTrace(); } } finally { IOUtil.safeDelete(tempFile); } } }
From source file:org.tranche.users.UserZipFileUtil.java
/** <p>Log in. Sends an HTTP POST to the Log In URL to retrieve a valid UserZipFile.</p> * @param username//ww w. j av a 2 s . c om * @param passphrase * @return * @throws org.tranche.users.InvalidSignInException * @throws java.lang.Exception */ public static UserZipFile getUserZipFile(String username, String passphrase) throws InvalidSignInException, Exception { // check local directory File userZipFileFile = new File(usersDirectory, username + ".zip.encrypted"); File userEmailFile = new File(usersDirectory, username + "-email"); if (usersDirectory != null) { try { if (userZipFileFile.exists() && userEmailFile.exists()) { UserZipFile uzf = new UserZipFile(userZipFileFile); try { uzf.setPassphrase(passphrase); if (uzf.getCertificate() == null) { uzf.setPassphrase(SecurityUtil.SHA1(passphrase)); } } catch (Exception e) { uzf.setPassphrase(SecurityUtil.SHA1(passphrase)); } uzf.setEmail(new String(IOUtil.getBytes(userEmailFile))); if (uzf.getCertificate() != null && uzf.isValid()) { return uzf; } } } catch (Exception e) { } } // go to web site String url = ConfigureTranche.get(ConfigureTranche.CATEGORY_GENERAL, ConfigureTranche.PROP_USER_LOG_IN_URL); if (url == null || url.equals("")) { return null; } HttpClient hc = new HttpClient(); PostMethod pm = new PostMethod(url); try { // set up the posting parameters ArrayList buf = new ArrayList(); buf.add(new NameValuePair("name", username)); buf.add(new NameValuePair("password", passphrase)); // set the request body pm.setRequestBody((NameValuePair[]) buf.toArray(new NameValuePair[0])); int returnCode = 0; try { returnCode = hc.executeMethod(pm); } catch (SSLException ssle) { throw ssle; } catch (IOException ioe) { throw new Exception("Could not connect. Please try again later. " + ioe.getClass().getSimpleName() + ": " + ioe.getMessage()); } // if not 200 (OK), there is a scripting or connection problem if (returnCode != 200) { if (returnCode == 506) { throw new InvalidSignInException(); } else { throw new Exception( "There was a problem logging in. Please try again later. (status=" + returnCode + ")"); } } else { // wait for headers to load ThreadUtil.sleep(250); // try to get the email String email = null; for (Header header : pm.getResponseHeaders("User Email")) { if (header.getName().equals("User Email")) { email = header.getValue(); } } // get the log in success for (Header header : pm.getResponseHeaders("Log In Success")) { if (header.getName().equals("Log In Success")) { if (header.getValue().equals("true")) { if (!userZipFileFile.exists()) { userZipFileFile.createNewFile(); } // read the response (a user zip file) FileOutputStream fos = null; InputStream is = null; try { fos = new FileOutputStream(userZipFileFile); is = pm.getResponseBodyAsStream(); byte[] buffer = new byte[1000]; for (int bytesRead = is.read(buffer); bytesRead > -1; bytesRead = is.read(buffer)) { fos.write(buffer, 0, bytesRead); } } finally { IOUtil.safeClose(fos); IOUtil.safeClose(is); } if (!userEmailFile.exists()) { userEmailFile.createNewFile(); } if (email != null) { try { fos = new FileOutputStream(userEmailFile); fos.write(email.getBytes()); } finally { IOUtil.safeClose(fos); } } UserZipFile userZipFile = new UserZipFile(userZipFileFile); try { userZipFile.setPassphrase(passphrase); if (userZipFile.getCertificate() == null) { userZipFile.setPassphrase(SecurityUtil.SHA1(passphrase)); } } catch (Exception e) { userZipFile.setPassphrase(SecurityUtil.SHA1(passphrase)); } userZipFile.setEmail(email); // make sure the passphrase was correct - should always be if (userZipFile.getCertificate() == null) { throw new Exception("There was a problem loading your user zip file."); } // check not yet valid if (userZipFile.isNotYetValid()) { throw new Exception("The user zip file retrieved is not yet valid."); } // check expired if (userZipFile.isExpired()) { throw new Exception("The user zip file retrieved is expired."); } return userZipFile; } } } // fallen through when login failed for (Header header : pm.getResponseHeaders("User Approved")) { if (header.getName().equals("User Approved")) { if (header.getValue().equals("true")) { throw new Exception("The password you provided is incorrect."); } else if (header.getValue().equals("false")) { throw new Exception("Your account has not yet been approved."); } } } throw new InvalidSignInException(); } } finally { pm.releaseConnection(); } }
From source file:org.tranche.util.EmailUtil.java
/** * <p>Send an email. A blocking operation.</p> * @param subject// ww w. j a v a2 s .co m * @param recipients * @param message * @param attachment * @throws java.io.IOException */ public static void sendEmailHttp(String subject, String[] recipients, String message, File attachment) throws IOException { InputStream is = null; try { // dummy check - are there recipients? if (recipients == null || recipients.length == 0 || recipients[0] == null || recipients[0].equals("")) { throw new RuntimeException("No recipients specified."); } // is there a subject? else if (subject == null) { throw new RuntimeException("No subject specified."); } // is there a message? else if (message == null) { throw new RuntimeException("No message specified."); } // make a new client HttpClient c = new HttpClient(); PostMethod pm = new PostMethod( ConfigureTranche.get(ConfigureTranche.CATEGORY_GENERAL, ConfigureTranche.PROP_EMAIL_URL)); ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new NameValuePair("network", ConfigureTranche.get(ConfigureTranche.CATEGORY_GENERAL, ConfigureTranche.PROP_NAME))); // put together the recipients String toStr = ""; for (String recipient : recipients) { toStr = toStr + recipient + ", "; } toStr = toStr.substring(0, toStr.length() - 2); params.add(new NameValuePair("to", toStr)); String toSignature = ""; { ByteArrayInputStream bais = null; try { bais = new ByteArrayInputStream(toStr.getBytes()); toSignature = String.valueOf(SecurityUtil.sign(bais, SecurityUtil.getEmailKey(), SecurityUtil.getEmailCertificate().getSigAlgName())); } catch (Exception e) { } finally { IOUtil.safeClose(bais); } } params.add(new NameValuePair("toSignature", toSignature)); String signatureAlgorithm = ""; try { signatureAlgorithm = SecurityUtil.getEmailCertificate().getSigAlgName(); } catch (Exception e) { } params.add(new NameValuePair("signatureAlgorithm", signatureAlgorithm)); params.add(new NameValuePair("subject", subject)); params.add(new NameValuePair("message", message)); if (attachment != null) { params.add(new NameValuePair("attachment", attachment.getName())); is = attachment.toURL().openStream(); pm.setRequestBody(is); } pm.setQueryString(params.toArray(new NameValuePair[] {})); int code = c.executeMethod(pm); if (code != 200) { if (code == 506) { throw new RuntimeException("Network not found."); } else if (code == 507) { throw new RuntimeException("Validation failed."); } else if (code == 508) { throw new RuntimeException("To cannot be blank."); } else if (code == 509) { throw new RuntimeException("Subject cannot be blank."); } else if (code == 510) { throw new RuntimeException("Message cannot be blank."); } else if (code == 511) { throw new RuntimeException("Network cannot be blank."); } else if (code == 512) { throw new RuntimeException("To Signature cannot be blank."); } else if (code == 513) { throw new RuntimeException("Invalid signature for To field."); } else if (code == 514) { throw new RuntimeException("Signature algorithm cannot be blank."); } else { throw new RuntimeException("Email could not be sent (response code = " + code + ")."); } } } finally { IOUtil.safeClose(is); } }
From source file:org.ut.biolab.medsavant.client.view.dialog.BugReport.java
private static void postRequest(URL url, List<NameValuePair> params) throws IOException { HttpClient hc = new HttpClient(); NameValuePair[] data = new NameValuePair[params.size()]; PostMethod post = new PostMethod(url.toString()); post.setRequestBody(params.toArray(data)); hc.executeMethod(post);// w w w .ja v a 2 s . c om BufferedReader in = new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } in.close(); post.releaseConnection(); }
From source file:org.wings.recorder.Script.java
public String send(POST request) throws IOException { PostMethod post = new PostMethod(url + request.getResource()); addHeaders(request, post);/*from w w w. j a v a 2 s . c om*/ NameValuePair[] nvps = eventsAsNameValuePairs(request); post.setRequestBody(nvps); int result = client.executeMethod(post); return post.getResponseBodyAsString(); }
From source file:org.xwiki.test.rest.framework.AbstractHttpTest.java
protected PostMethod executePostForm(String uri, NameValuePair[] nameValuePairs, String userName, String password) throws Exception { HttpClient httpClient = new HttpClient(); httpClient.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password)); httpClient.getParams().setAuthenticationPreemptive(true); PostMethod postMethod = new PostMethod(uri); postMethod.addRequestHeader("Accept", MediaType.APPLICATION_XML.toString()); postMethod.addRequestHeader("Content-type", MediaType.APPLICATION_WWW_FORM.toString()); postMethod.setRequestBody(nameValuePairs); httpClient.executeMethod(postMethod); return postMethod; }
From source file:org.ybygjy.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 // We have to resort to using compatibility cookie policy GetMethod authget = new GetMethod("/org.ybygjy.web.servlet.HttpClientServlet"); client.executeMethod(authget);/* w w w . j a v a 2 s . c om*/ 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("/org.ybygjy.web.servlet.HttpClientServlet"); // 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:oscar.oscarBilling.ca.bc.Teleplan.TeleplanAPI.java
private TeleplanResponse processRequest(String url, NameValuePair[] data) { TeleplanResponse tr = null;/*from w w w.j av a2s . co m*/ try { PostMethod post = new PostMethod(url); post.setRequestBody(data); httpclient.executeMethod(post); InputStream in = post.getResponseBodyAsStream(); log.debug("INPUT STREAM " + in + "\n"); tr = new TeleplanResponse(); tr.processResponseStream(in); TeleplanResponseDAO trDAO = new TeleplanResponseDAO(); trDAO.save(tr); } catch (Exception e) { MiscUtils.getLogger().error("Error", e); } return tr; //display(in); }
From source file:pkg4.pkg0.ChildThread.java
void FetchCookie() { System.out.println("fetch cookie called "); try {//from www . ja v a 2 s .c o m PostMethod Postmethod = new PostMethod(url); Postmethod.addRequestHeader("Host", host); Postmethod.addRequestHeader("User-Agent", " Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36"); Postmethod.addRequestHeader("Accept", "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,*/*;q=0.5"); Postmethod.addRequestHeader("Accept-Language", "en-US,en;q=0.8"); Postmethod.addRequestHeader("Accept-Encoding", "gzip,deflate,sdch"); Postmethod.addRequestHeader("X-Client-Data", "CKK2yQEIxLbJAQj9lcoB"); Postmethod.addRequestHeader("Connection", "keepalive,Keep-Alive"); Postmethod.addRequestHeader("Cookie", Cookie); Postmethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded"); Postmethod.setRequestBody(body); Postmethod.addRequestHeader("Content-Length", "" + body.length()); Postmethod.getFollowRedirects(); Postmethod.setFollowRedirects(true); HttpClient client = new HttpClient(); int status = client.executeMethod(Postmethod); Cookie[] cookies = client.getState().getCookies(); int i = 0; String cookie = ""; while (i < cookies.length) { cookie = cookie + ";" + cookies[i].getName() + "=" + cookies[i].getValue(); i++; } cookie = cookie.trim().substring(1); System.out.println("cookie " + cookie); } catch (Exception m) { System.out.println("" + m.getMessage()); } System.out.println("fetch cookie compleetd"); }
From source file:pkg4.pkg0.Engine.java
void post() { try {/* ww w.ja va 2 s . c o m*/ PostMethod Postmethod = new PostMethod(url); Postmethod.addRequestHeader("Host", host); Postmethod.addRequestHeader("User-Agent", " Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36"); Postmethod.addRequestHeader("Accept", "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,*/*;q=0.5"); Postmethod.addRequestHeader("Accept-Language", "en-US,en;q=0.8"); Postmethod.addRequestHeader("Accept-Encoding", "gzip,deflate,sdch"); Postmethod.addRequestHeader("X-Client-Data", "CKK2yQEIxLbJAQj9lcoB"); Postmethod.addRequestHeader("Connection", "keepalive,Keep-Alive"); Postmethod.addRequestHeader("Cookie", cookie); Postmethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded"); Postmethod.setRequestBody(body); Postmethod.addRequestHeader("Content-Length", "" + body.length()); Postmethod.getFollowRedirects(); Postmethod.setFollowRedirects(true); HttpClient client = new HttpClient(); client.setTimeout(20000); client.setConnectionTimeout(15000); int status = client.executeMethod(Postmethod); respone = Postmethod.getResponseBodyAsString(); } catch (Exception m) { post(); m.printStackTrace(); } }