List of usage examples for org.apache.commons.httpclient.methods PostMethod addParameter
public void addParameter(String paramString1, String paramString2) throws IllegalArgumentException
From source file:com.alta189.cyborg.commit.ShortUrlService.java
public static String shorten(String url, String keyword) { switch (service) { case BIT_LY://from w w w. ja v a 2 s .co m HttpClient httpclient = new HttpClient(); HttpMethod method = new GetMethod("http://api.bit.ly/shorten"); method.setQueryString( new NameValuePair[] { new NameValuePair("longUrl", url), new NameValuePair("version", "2.0.1"), new NameValuePair("login", user), new NameValuePair("apiKey", apiKey), new NameValuePair("format", "xml"), new NameValuePair("history", "1") }); try { httpclient.executeMethod(method); String responseXml = method.getResponseBodyAsString(); String retVal = null; if (responseXml != null) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); StringReader st = new StringReader(responseXml); Document d = db.parse(new InputSource(st)); NodeList nl = d.getElementsByTagName("shortUrl"); if (nl != null) { Node n = nl.item(0); retVal = n.getTextContent(); } } return retVal; } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } return null; case SPOUT_IN: HttpClient client = new HttpClient(); String result = null; client.getParams().setParameter("http.useragent", "Test Client"); BufferedReader br = null; PostMethod pMethod = new PostMethod("http://spout.in/yourls-api.php"); pMethod.addParameter("signature", apiKey); pMethod.addParameter("action", "shorturl"); pMethod.addParameter("format", "simple"); pMethod.addParameter("url", url); if (keyword != null) { pMethod.addParameter("keyword", keyword); } try { int returnCode = client.executeMethod(pMethod); if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) { System.err.println("The Post method is not implemented by this URI"); pMethod.getResponseBodyAsString(); } else { br = new BufferedReader(new InputStreamReader(pMethod.getResponseBodyAsStream())); String readLine; if (((readLine = br.readLine()) != null)) { result = readLine; } } } catch (Exception e) { System.err.println(e); } finally { pMethod.releaseConnection(); if (br != null) { try { br.close(); } catch (Exception fe) { fe.printStackTrace(); } } } return result; } return null; }
From source file:de.mpg.escidoc.services.tools.scripts.person_grants.Util.java
/** * Logs in the given user with the given password. * /*from w w w . j a v a 2 s . co m*/ * @param userid The id of the user to log in. * @param password The password of the user to log in. * @return The handle for the logged in user. * @throws HttpException * @throws IOException * @throws ServiceException * @throws URISyntaxException */ public static String loginUser(String userid, String password, String frameworkUrl) throws HttpException, IOException, ServiceException, URISyntaxException { int delim1 = frameworkUrl.indexOf("//"); int delim2 = frameworkUrl.indexOf(":", delim1); String host; int port; if (delim2 > 0) { host = frameworkUrl.substring(delim1 + 2, delim2); port = Integer.parseInt(frameworkUrl.substring(delim2 + 1)); } else { host = frameworkUrl.substring(delim1 + 2); port = 80; } HttpClient client = new HttpClient(); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); PostMethod login = new PostMethod(frameworkUrl + "/aa/j_spring_security_check"); login.addParameter("j_username", userid); login.addParameter("j_password", password); client.executeMethod(login); login.releaseConnection(); CookieSpec cookiespec = CookiePolicy.getDefaultSpec(); // Cookie[] logoncookies = cookiespec.match(host, port, "/", false, client.getState().getCookies()); Cookie sessionCookie = client.getState().getCookies()[0]; PostMethod postMethod = new PostMethod(frameworkUrl + "/aa/login"); postMethod.addParameter("target", frameworkUrl); client.getState().addCookie(sessionCookie); client.executeMethod(postMethod); if (HttpStatus.SC_SEE_OTHER != postMethod.getStatusCode()) { throw new HttpException("Wrong status code: " + login.getStatusCode()); } String userHandle = null; Header headers[] = postMethod.getResponseHeaders(); for (int i = 0; i < headers.length; ++i) { if ("Location".equals(headers[i].getName())) { String location = headers[i].getValue(); int index = location.indexOf('='); userHandle = new String(Base64.decode(location.substring(index + 1, location.length()))); // System.out.println("location: "+location); // System.out.println("handle: "+userHandle); } } if (userHandle == null) { throw new ServiceException("User not logged in."); } return userHandle; }
From source file:de.mpg.escidoc.services.framework.AdminHelper.java
/** * Logs in the given user with the given password. * // w ww.java 2s. co m * @param userid The id of the user to log in. * @param password The password of the user to log in. * @return The handle for the logged in user. * @throws HttpException * @throws IOException * @throws ServiceException * @throws URISyntaxException */ public static String loginUser(String userid, String password) throws HttpException, IOException, ServiceException, URISyntaxException { String frameworkUrl = ServiceLocator.getLoginUrl(); int delim1 = frameworkUrl.indexOf("//"); int delim2 = frameworkUrl.indexOf(":", delim1); String host; int port; if (delim2 > 0) { host = frameworkUrl.substring(delim1 + 2, delim2); port = Integer.parseInt(frameworkUrl.substring(delim2 + 1)); } else { host = frameworkUrl.substring(delim1 + 2); port = 80; } HttpClient client = new HttpClient(); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); PostMethod login = new PostMethod(frameworkUrl + "/aa/j_spring_security_check"); login.addParameter("j_username", userid); login.addParameter("j_password", password); ProxyHelper.executeMethod(client, login); login.releaseConnection(); CookieSpec cookiespec = CookiePolicy.getDefaultSpec(); Cookie[] logoncookies = cookiespec.match(host, port, "/", false, client.getState().getCookies()); Cookie sessionCookie = logoncookies[0]; PostMethod postMethod = new PostMethod(frameworkUrl + "/aa/login"); postMethod.addParameter("target", frameworkUrl); client.getState().addCookie(sessionCookie); ProxyHelper.executeMethod(client, postMethod); if (HttpServletResponse.SC_SEE_OTHER != postMethod.getStatusCode()) { throw new HttpException("Wrong status code: " + login.getStatusCode()); } String userHandle = null; Header headers[] = postMethod.getResponseHeaders(); for (int i = 0; i < headers.length; ++i) { if ("Location".equals(headers[i].getName())) { String location = headers[i].getValue(); int index = location.indexOf('='); userHandle = new String(Base64.decode(location.substring(index + 1, location.length()))); //System.out.println("location: "+location); //System.out.println("handle: "+userHandle); } } if (userHandle == null) { throw new ServiceException("User not logged in."); } return userHandle; }
From source file:cn.vlabs.duckling.common.http.WebSite.java
public static String getBodyContent(String url) { int index = url.indexOf("?"); String query = ""; if (index > 0) { query = url.substring(index + 1, url.length()); url = url.substring(0, index);// ww w . j a v a 2 s .c o m } WebSite site = new WebSite(url); if (query.trim().length() > 0) { PostMethod method = site.createPostMethod(null); Map<String, String> params = extractParams(query.trim()); for (String key : params.keySet()) { method.addParameter(key, params.get(key)); } try { int code = site.exec(method); if (code == 200) { return method.getResponseBodyAsString(); } } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { method.releaseConnection(); site.close(); } } else { GetMethod method = site.createGetMethod(""); try { int code = site.exec(method); if (code == 200) { return method.getResponseBodyAsString(); } } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { method.releaseConnection(); site.close(); } } return null; }
From source file:de.mpg.imeji.presentation.util.Scripts.java
public static String login(String frameworkUrl, String userName, String password) throws Exception { StringTokenizer tokens = new StringTokenizer(frameworkUrl, "//"); tokens.nextToken();/* www . j av a 2s.com*/ StringTokenizer hostPort = new StringTokenizer(tokens.nextToken(), ":"); String host = hostPort.nextToken(); int port = Integer.parseInt(hostPort.nextToken()); HttpClient client = new HttpClient(); client.getHostConfiguration().setHost(host, port, "http"); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); PostMethod login = new PostMethod(frameworkUrl + "/aa/j_spring_security_check"); login.addParameter("j_username", userName); login.addParameter("j_password", password); client.executeMethod(login); //System.out.println("Login form post: " + login.getStatusLine().toString()); login.releaseConnection(); CookieSpec cookiespec = CookiePolicy.getDefaultSpec(); Cookie[] logoncookies = cookiespec.match(host, port, "/", false, client.getState().getCookies()); Cookie sessionCookie = logoncookies[0]; PostMethod postMethod = new PostMethod("/aa/login"); postMethod.addParameter("target", frameworkUrl); client.getState().addCookie(sessionCookie); client.executeMethod(postMethod); //System.out.println("Login second post: " + postMethod.getStatusLine().toString()); if (HttpServletResponse.SC_SEE_OTHER != postMethod.getStatusCode()) { throw new HttpException("Wrong status code: " + login.getStatusCode()); } String userHandle = null; Header headers[] = postMethod.getResponseHeaders(); for (int i = 0; i < headers.length; ++i) { if ("Location".equals(headers[i].getName())) { String location = headers[i].getValue(); int index = location.indexOf('='); userHandle = new String(Base64.decode(location.substring(index + 1, location.length()))); //System.out.println("location: "+location); //System.out.println("handle: "+userHandle); } } if (userHandle == null) { throw new ServiceException("User not logged in."); } return userHandle; }
From source file:dashboard.ImportCDN.java
public static int postRequest(String url, String p1, String v1, String p2, String v2) { int statusCode = -1; try {//from w w w. j a v a 2s.c o m String contents = ""; int result = 0; HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); // Configure the form parameters method.addParameter(p1, v1); method.addParameter(p2, v2); // Add more details in the POST response method.addParameter("verbose", "1"); // Execute the POST method statusCode = client.executeMethod(method); if (statusCode == 200) { contents = method.getResponseBodyAsString(); if (contents.charAt(11) == '1') result = 1; } method.releaseConnection(); if (statusCode != 200 || result != 1) { // Post to Mixpanel Failed System.out.println("Mixpanel Post respone: " + Integer.toString(statusCode) + " - " + contents); return 0; } return 1; } catch (Exception e) { //e.printStackTrace(); System.out.println("Exception when calling Mixpanel POST. Response: " + statusCode); return 0; } }
From source file:fr.cls.atoll.motu.library.misc.cas.TestCASRest.java
public static Cookie[] validateFromCAS2(String username, String password) throws Exception { String url = casServerUrlPrefix + "/v1/tickets?"; String s = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8"); s += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8"); 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); // Create an instance of HttpClient. // HttpClient client = new HttpClient(); HttpClient client = new HttpClient(); Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 8443); URI uri = new URI(url + s, true); // use relative url only PostMethod httpget = new PostMethod(url); httpget.addParameter("username", username); httpget.addParameter("password", password); HostConfiguration hc = new HostConfiguration(); hc.setHost("atoll-dev.cls.fr", 8443, easyhttps); // client.executeMethod(hc, httpget); client.setState(initialState);/* ww w .j a v a 2s. c o m*/ // Create a method instance. System.out.println(url + s); GetMethod method = new GetMethod(url + s); // GetMethod method = new GetMethod(url ); HostConfiguration hostConfiguration = new HostConfiguration(); hostConfiguration.setProxy("proxy.cls.fr", 8080); client.setHostConfiguration(hostConfiguration); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); // String username = "xxx"; // String password = "xxx"; // Credentials credentials = new UsernamePasswordCredentials(username, password); // AuthScope authScope = new AuthScope("proxy.cls.fr", 8080); // // client.getState().setProxyCredentials(authScope, credentials); Cookie[] cookies = null; try { // Execute the method. // int statusCode = client.executeMethod(method); int statusCode = client.executeMethod(hc, httpget); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + method.getStatusLine()); } for (Header header : method.getRequestHeaders()) { System.out.println(header.getName()); System.out.println(header.getValue()); } // Read the response body. byte[] responseBody = method.getResponseBody(); // Deal with the response. // Use caution: ensure correct character encoding and is not binary data System.out.println(new String(responseBody)); System.out.println("Response status code: " + statusCode); // Get all the cookies cookies = client.getState().getCookies(); // Display the cookies System.out.println("Present cookies: "); for (int i = 0; i < cookies.length; i++) { System.out.println(" - " + cookies[i].toExternalForm()); } Assertion assertion = AssertionHolder.getAssertion(); if (assertion == null) { System.out.println("<p>Assertion is null</p>"); } } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // Release the connection. method.releaseConnection(); } return cookies; }
From source file:edu.unc.lib.dl.ui.util.FileIOUtil.java
public static String postImport(HttpServletRequest request, String url) { Map<String, String[]> parameters = request.getParameterMap(); HttpClientParams params = new HttpClientParams(); params.setContentCharset("UTF-8"); HttpClient client = new HttpClient(); client.setParams(params);//from w w w . j a v a2s . c o m PostMethod post = new PostMethod(url); Iterator<Entry<String, String[]>> parameterIt = parameters.entrySet().iterator(); while (parameterIt.hasNext()) { Entry<String, String[]> parameter = parameterIt.next(); for (String parameterValue : parameter.getValue()) { post.addParameter(parameter.getKey(), parameterValue); } } try { client.executeMethod(post); return post.getResponseBodyAsString(); } catch (Exception e) { throw new ResourceNotFoundException("Failed to retrieve POST import request for " + url, e); } finally { post.releaseConnection(); } }
From source file:com.tops.hotelmanager.util.CommonHttpClient.java
public static String executePostRequest(String url, Map<String, String> map, Map<String, String> header, int timeOut) { HttpClient client = new HttpClient(); // HostConfiguration configuration = new HostConfiguration(); // configuration.setProxy("localhost", 8888); // client.setHostConfiguration(configuration); client.getHttpConnectionManager().getParams().setSoTimeout(timeOut); client.getHttpConnectionManager().getParams().setConnectionTimeout(timeOut); PostMethod post = new PostMethod(url); try {//from ww w. j av a 2s .c o m if (map != null && map.size() > 0) { for (Map.Entry<String, String> entry : map.entrySet()) { post.addParameter(entry.getKey(), entry.getValue()); } } if (header != null && header.size() > 0) { for (Map.Entry<String, String> entry : header.entrySet()) { post.addRequestHeader(entry.getKey(), entry.getValue()); } } int i = client.executeMethod(post); if (i != -1) { return post.getResponseBodyAsString(); } } catch (Exception e) { logger.error("HttpClient post method error url: " + url + ", Parameters: " + map, e); } finally { if (post != null) { post.releaseConnection(); } } return "error~Request Failed"; }
From source file:kevin.gvmsgarch.Worker.java
private static void archiveThese(String authToken, String rsrse, Collection<String> msgIds, ArchiveMode mode) throws HttpException, IOException { HttpClient c = new HttpClient(); PostMethod m = new PostMethod("https://www.google.com/voice/inbox/" + mode.getUriFragment() + "/"); for (String msgid : msgIds) { m.addParameter("messages", msgid); }/*from www.j a va2s .c om*/ if (!mode.labelString().trim().isEmpty()) { m.addParameter(mode.labelString(), mode.labelStringValue()); } m.addParameter("_rnr_se", rsrse); m.setRequestHeader("Authorization", "GoogleLogin auth=" + authToken); int rcode; rcode = c.executeMethod(m); if (rcode != 200) { throw new RuntimeException("Received rcode: " + rcode); } }