List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestBody
public void setRequestBody(NameValuePair[] paramArrayOfNameValuePair) throws IllegalArgumentException
From source file:mapbuilder.ProxyRedirect.java
/*************************************************************************** * Process the HTTP Post request/*from w w w . jav a 2 s.co m*/ */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { try { if (log.isDebugEnabled()) { Enumeration e = request.getHeaderNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); String value = request.getHeader(name); log.debug("request header:" + name + ":" + value); } } String serverUrl = request.getHeader("serverUrl"); if (serverUrl.startsWith("http://") || serverUrl.startsWith("https://")) { PostMethod httppost = new PostMethod(serverUrl); // Transfer bytes from in to out log.info("HTTP POST transfering..." + serverUrl); String body = inputStreamAsString(request.getInputStream()); HttpClient client = new HttpClient(); httppost.setRequestBody(body); if (0 == httppost.getParameters().length) { log.debug("No Name/Value pairs found ... pushing as raw_post_data"); httppost.setParameter("raw_post_data", body); } if (log.isDebugEnabled()) { log.debug("Body = " + body); NameValuePair[] nameValuePairs = httppost.getParameters(); log.debug("NameValuePairs found: " + nameValuePairs.length); for (int i = 0; i < nameValuePairs.length; ++i) { log.debug("parameters:" + nameValuePairs[i].toString()); } } //httppost.setRequestContentLength(PostMethod.CONTENT_LENGTH_CHUNKED); client.executeMethod(httppost); if (log.isDebugEnabled()) { Header[] respHeaders = httppost.getResponseHeaders(); for (int i = 0; i < respHeaders.length; ++i) { String headerName = respHeaders[i].getName(); String headerValue = respHeaders[i].getValue(); log.debug("responseHeaders:" + headerName + "=" + headerValue); } } if (httppost.getStatusCode() == HttpStatus.SC_OK) { response.setContentType("text/xml"); String responseBody = httppost.getResponseBodyAsString(); // use encoding of the request or UTF8 String encoding = request.getCharacterEncoding(); if (encoding == null) encoding = "UTF-8"; response.setCharacterEncoding(encoding); log.info("responseEncoding:" + encoding); // do not set a content-length of the response (string length might not match the response byte size) //response.setContentLength(responseBody.length()); log.info("responseBody:" + responseBody); PrintWriter out = response.getWriter(); out.print(responseBody); } else { log.error("Unexpected failure: " + httppost.getStatusLine().toString()); } httppost.releaseConnection(); } else { throw new ServletException("only HTTP(S) protocol supported"); } } catch (Throwable e) { throw new ServletException(e); } }
From source file:com.dtolabs.client.utils.BaseFormAuthenticator.java
/** * Authenticate the client http state so that the colony requests can be made. * * @param baseURL URL requested for colony * @param client HttpClient instance/* w w w. j a va 2 s . c om*/ * * @return true if authentication succeeded. * * @throws com.dtolabs.client.utils.HttpClientException * */ public boolean authenticate(final URL baseURL, final HttpClient client) throws HttpClientException { final HttpState state = client.getState(); if (hasSessionCookie(baseURL, state, basePath)) { return true; } final byte[] buffer = new byte[1024]; boolean doPostLogin = false; boolean isLoginFormContent = false; logger.debug("No session found, must login..."); try { final URL newUrl = new URL(baseURL.getProtocol(), baseURL.getHost(), baseURL.getPort(), basePath + getInitialPath()); //load welcome page, which should forward to form based logon page. final GetMethod get = new GetMethod(newUrl.toExternalForm()); get.setDoAuthentication(false); get.setFollowRedirects(false); logger.debug("Requesting: " + newUrl); int res = client.executeMethod(get); logger.debug("Result is: " + res); /* Tomcat container auth behaves differently than Jetty. Tomcat will respond 200 OK and include the login form when auth is required, as well as on auth failure, it will also require complete GET of original URL after successful auth. Jetty will redirect to login page when auth is required, and will redirect to error page on failure. */ String body = get.getResponseBodyAsString(); if (null != body && body.contains(J_SECURITY_CHECK) && body.contains(JAVA_USER_PARAM) && body.contains(JAVA_PASS_PARAM)) { isLoginFormContent = true; } get.releaseConnection(); if ((res == HttpStatus.SC_UNAUTHORIZED)) { if (get.getResponseHeader("WWW-Authenticate") != null && get.getResponseHeader("WWW-Authenticate").getValue().matches("^Basic.*")) { logger.warn("Form-based login received UNAUTHORIZED, trying to use Basic authentication"); final BasicAuthenticator auth = new BasicAuthenticator(username, password); return auth.authenticate(baseURL, client); } else { throw new HttpClientException( "Form-based login received UNAUTHORIZED, but didn't recognize it as Basic authentication: unable to get a session"); } } //should now have the proper session cookie if (!hasSessionCookie(baseURL, state, basePath)) { throw new HttpClientException("Unable to get a session from URL : " + newUrl); } if (res == HttpStatus.SC_OK && isLoginFormContent) { doPostLogin = true; } else if ((res == HttpStatus.SC_MOVED_TEMPORARILY) || (res == HttpStatus.SC_MOVED_PERMANENTLY) || (res == HttpStatus.SC_SEE_OTHER) || (res == HttpStatus.SC_TEMPORARY_REDIRECT)) { Header locHeader = get.getResponseHeader("Location"); if (locHeader == null) { throw new HttpClientException("Redirect with no Location header, request URL: " + newUrl); } String location = locHeader.getValue(); if (!isValidLoginRedirect(get)) { //unexpected response throw new HttpClientException("Unexpected redirection when getting session: " + location); } logger.debug("Follow redirect: " + res + ": " + location); final GetMethod redir = new GetMethod(location); redir.setFollowRedirects(true); res = client.executeMethod(redir); InputStream ins = redir.getResponseBodyAsStream(); while (ins.available() > 0) { //read and discard response body ins.read(buffer); } redir.releaseConnection(); if (res != HttpStatus.SC_OK) { throw new HttpClientException("Login page status was not OK: " + res); } logger.debug("Result: " + res); doPostLogin = true; } else if (res != HttpStatus.SC_OK) { //if request to welcome page was OK, we figure that the session is already set throw new HttpClientException("Request to welcome page returned error: " + res + ": " + get); } if (doPostLogin) { //now post login final URL loginUrl = new URL(baseURL.getProtocol(), baseURL.getHost(), baseURL.getPort(), basePath + JAVA_AUTH_PATH); final PostMethod login = new PostMethod(loginUrl.toExternalForm()); login.setRequestBody(new NameValuePair[] { new NameValuePair(JAVA_USER_PARAM, getUsername()), new NameValuePair(JAVA_PASS_PARAM, getPassword()) }); login.setFollowRedirects(false); logger.debug("Post login info to URL: " + loginUrl); res = client.executeMethod(login); final InputStream ins = login.getResponseBodyAsStream(); while (ins.available() > 0) { //read and discard response body ins.read(buffer); } login.releaseConnection(); Header locHeader = login.getResponseHeader("Location"); String location = null != locHeader ? locHeader.getValue() : null; if (isLoginError(login)) { logger.error("Form-based auth failed"); return false; } else if (null != location && !location.equals(newUrl.toExternalForm())) { logger.warn("Form-based auth succeeded, but last URL was unexpected"); } if (isFollowLoginRedirect() && ((res == HttpStatus.SC_MOVED_TEMPORARILY) || (res == HttpStatus.SC_MOVED_PERMANENTLY) || (res == HttpStatus.SC_SEE_OTHER) || (res == HttpStatus.SC_TEMPORARY_REDIRECT))) { if (location == null) { throw new HttpClientException("Redirect with no Location header, request URL: " + newUrl); } final GetMethod get2 = new GetMethod(location); // logger.debug("Result: " + res + ": " + location + ", following redirect"); res = client.executeMethod(get2); } else if (res != HttpStatus.SC_OK) { throw new HttpClientException( "Login didn't seem to work: " + res + ": " + login.getResponseBodyAsString()); } logger.debug("Result: " + res); } } catch (MalformedURLException e) { throw new HttpClientException("Bad URL", e); } catch (HttpException e) { throw new HttpClientException("HTTP Error: " + e.getMessage(), e); } catch (IOException e) { throw new HttpClientException( "Error occurred while trying to authenticate to server: " + e.getMessage(), e); } return true; }
From source file:com.compomics.mslims.util.mascot.MascotWebConnector.MascotAuthenticatedConnection.java
/** * Create a login post method for the mascot server * @param username/*from www . j a va2 s . c om*/ * @param password * @return the prepared post method * @throws java.lang.IllegalArgumentException */ private PostMethod loginMethod(String username, String password) { PostMethod authpost = new PostMethod("/mascot/cgi/login.pl"); // Prepare login parameters NameValuePair[] arguments = { new NameValuePair("action", "login"), new NameValuePair("username", username), new NameValuePair("password", password), new NameValuePair("display", "logout_prompt"), new NameValuePair("savecookie", "1"), new NameValuePair("onerrdisplay", "login_prompt"), }; authpost.setRequestBody(arguments); return authpost; }
From source file:com.sapienter.jbilling.server.process.AgeingBL.java
public void setUserStatus(Integer executorId, Integer userId, Integer statusId, Date today) { // find out if this user is not already in the required status UserBL user = new UserBL(userId); Integer originalStatusId = user.getEntity().getStatus().getId(); if (originalStatusId.equals(statusId)) { return;/*from w w w . ja va 2 s.c o m*/ } LOG.debug("Setting user " + userId + " status to " + statusId); // see if this guy could login in her present status boolean couldLogin = user.getEntity().getStatus().getCanLogin() == 1; // log an event if (executorId != null) { // this came from the gui eLogger.audit(executorId, userId, Constants.TABLE_BASE_USER, user.getEntity().getUserId(), EventLogger.MODULE_USER_MAINTENANCE, EventLogger.STATUS_CHANGE, user.getEntity().getStatus().getId(), null, null); } else { // this is from a process, no executor involved eLogger.auditBySystem(user.getEntity().getEntity().getId(), userId, Constants.TABLE_BASE_USER, user.getEntity().getUserId(), EventLogger.MODULE_USER_MAINTENANCE, EventLogger.STATUS_CHANGE, user.getEntity().getStatus().getId(), null, null); } // make the notification NotificationBL notification = new NotificationBL(); try { MessageDTO message = notification.getAgeingMessage(user.getEntity().getEntity().getId(), user.getEntity().getLanguageIdField(), statusId, userId); INotificationSessionBean notificationSess = (INotificationSessionBean) Context .getBean(Context.Name.NOTIFICATION_SESSION); notificationSess.notify(user.getEntity(), message); } catch (NotificationNotFoundException e) { LOG.warn("Changeing the satus of a user. An ageing notification " + "should be " + "sent to the user, but the entity doesn't have it. " + "entity " + user.getEntity().getEntity().getId()); } // make the change UserStatusDTO status = new UserStatusDAS().find(statusId); user.getEntity().setUserStatus(status); user.getEntity().setLastStatusChange(today); if (status.getId() == UserDTOEx.STATUS_DELETED) { // yikes, it's out user.delete(executorId); return; // her orders were deleted, no need for any change in status } // see if this new status is suspended if (couldLogin && status.getCanLogin() == 0) { // all the current orders have to be suspended OrderDAS orderDas = new OrderDAS(); OrderBL order = new OrderBL(); for (Iterator it = orderDas.findByUser_Status(userId, Constants.ORDER_STATUS_ACTIVE).iterator(); it .hasNext();) { OrderDTO orderRow = (OrderDTO) it.next(); order.set(orderRow); order.setStatus(executorId, Constants.ORDER_STATUS_SUSPENDED_AGEING); } } else if (!couldLogin && status.getCanLogin() == 1) { // the oposite, it is getting out of the ageing process // all the suspended orders have to be reactivated OrderDAS orderDas = new OrderDAS(); OrderBL order = new OrderBL(); for (Iterator it = orderDas.findByUser_Status(userId, Constants.ORDER_STATUS_SUSPENDED_AGEING) .iterator(); it.hasNext();) { OrderDTO orderRow = (OrderDTO) it.next(); order.set(orderRow); order.setStatus(executorId, Constants.ORDER_STATUS_ACTIVE); } } // make the http call back String url = null; try { PreferenceBL pref = new PreferenceBL(); pref.set(user.getEntity().getEntity().getId(), Constants.PREFERENCE_URL_CALLBACK); url = pref.getString(); } catch (EmptyResultDataAccessException e2) { // no call then } if (url != null && url.length() > 0) { // get the url connection try { LOG.debug("Making callback to " + url); // cook the parameters to be sent NameValuePair[] data = new NameValuePair[6]; data[0] = new NameValuePair("cmd", "ageing_update"); data[1] = new NameValuePair("user_id", userId.toString()); data[2] = new NameValuePair("login_name", user.getEntity().getUserName()); data[3] = new NameValuePair("from_status", originalStatusId.toString()); data[4] = new NameValuePair("to_status", statusId.toString()); data[5] = new NameValuePair("can_login", String.valueOf(status.getCanLogin())); // make the call HttpClient client = new HttpClient(); client.setConnectionTimeout(30000); PostMethod post = new PostMethod(url); post.setRequestBody(data); client.executeMethod(post); } catch (Exception e1) { LOG.info("Could not make call back. url = " + url + " Message:" + e1.getMessage()); } } // trigger NewUserStatusEvent EventManager.process( new NewUserStatusEvent(user.getDto().getCompany().getId(), userId, originalStatusId, statusId)); }
From source file:ixa.entity.linking.DBpediaSpotlightClient.java
public Document extract(Text text, int port) throws AnnotationException { LOG.info("Querying API."); String spotlightResponse = ""; Document doc = null;/* ww w.j av a 2s .com*/ try { String url = "http://localhost:" + port + "/rest/disambiguate"; PostMethod method = new PostMethod(url); method.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); NameValuePair[] params = { new NameValuePair("text", text.text()), new NameValuePair("spotter", "SpotXmlParser"), new NameValuePair("confidence", Double.toString(CONFIDENCE)), new NameValuePair("support", Integer.toString(SUPPORT)) }; method.setRequestBody(params); method.setRequestHeader(new Header("Accept", "text/xml")); spotlightResponse = request(method); doc = loadXMLFromString(spotlightResponse); } catch (javax.xml.parsers.ParserConfigurationException ex) { } catch (org.xml.sax.SAXException ex) { } catch (java.io.IOException ex) { } return doc; }
From source file:ixa.pipe.wikify.DBpediaSpotlightClient.java
public Document extract(Text text, String host, String port) throws AnnotationException { LOG.info("Querying API."); String spotlightResponse = ""; Document doc = null;//from w w w . ja v a2 s. c om try { String url = host + ":" + port + "/rest/annotate"; PostMethod method = new PostMethod(url); method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); NameValuePair[] params = { new NameValuePair("text", text.text()), new NameValuePair("confidence", Double.toString(CONFIDENCE)), new NameValuePair("support", Integer.toString(SUPPORT)), new NameValuePair("coreferenceResolution", Boolean.toString(COREFERENCE)) }; method.setRequestBody(params); method.setRequestHeader(new Header("Accept", "text/xml")); spotlightResponse = request(method); doc = loadXMLFromString(spotlightResponse); } catch (javax.xml.parsers.ParserConfigurationException ex) { } catch (org.xml.sax.SAXException ex) { } catch (java.io.IOException ex) { } return doc; }
From source file:it.geosdi.era.server.servlet.HTTPProxy.java
/** * Sets up the given {@link PostMethod} to send the same standard POST * data as was sent in the given {@link HttpServletRequest} * @param postMethodProxyRequest The {@link PostMethod} that we are * configuring to send a standard POST request * @param httpServletRequest The {@link HttpServletRequest} that contains * the POST data to be sent via the {@link PostMethod} *///from w ww. j a v a 2s. c om @SuppressWarnings("unchecked") private void handleStandardPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest) { try { postMethodProxyRequest.setRequestBody(httpServletRequest.getInputStream()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:ehu.ned.DBpediaSpotlightClient.java
public Document extract_with_endpoint(Text text, String endpoint) throws AnnotationException { LOG.info("Querying API at: " + endpoint); String spotlightResponse = ""; Document doc = null;//from ww w . j av a 2 s . c om try { PostMethod method = new PostMethod(endpoint); method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); NameValuePair[] params = { new NameValuePair("text", text.text()), new NameValuePair("spotter", "SpotXmlParser"), new NameValuePair("confidence", Double.toString(CONFIDENCE)), new NameValuePair("support", Integer.toString(SUPPORT)) }; method.setRequestBody(params); method.setRequestHeader(new Header("Accept", "text/xml")); spotlightResponse = request(method); doc = loadXMLFromString(spotlightResponse); } catch (javax.xml.parsers.ParserConfigurationException ex) { } catch (org.xml.sax.SAXException ex) { } catch (java.io.IOException ex) { } return doc; }
From source file:com.mirth.connect.client.core.UpdateClient.java
public void registerUser(User user) throws ClientException { HttpClientParams httpClientParams = new HttpClientParams(); HttpConnectionManager httpConnectionManager = new SimpleHttpConnectionManager(); httpClientParams.setSoTimeout(10 * 1000); httpConnectionManager.getParams().setConnectionTimeout(10 * 1000); httpConnectionManager.getParams().setSoTimeout(10 * 1000); HttpClient httpClient = new HttpClient(httpClientParams, httpConnectionManager); PostMethod post = new PostMethod(client.getUpdateSettings().getUpdateUrl() + URL_REGISTRATION); NameValuePair[] params = { new NameValuePair("serverId", client.getServerId()), new NameValuePair("version", client.getVersion()), new NameValuePair("user", serializer.toXML(user)) }; post.setRequestBody(params); try {// w w w . j ava2 s . c om int statusCode = httpClient.executeMethod(post); if ((statusCode != HttpStatus.SC_OK) && (statusCode != HttpStatus.SC_MOVED_TEMPORARILY)) { throw new Exception("Failed to connect to update server: " + post.getStatusLine()); } } catch (Exception e) { throw new ClientException(e); } finally { post.releaseConnection(); } }
From source file:com.mrfeinberg.translation.plugin.altavista.AltavistaTranslationService.java
@Override protected HttpMethod getHttpMethod(final String phrase, final LanguagePair lp) { final PostMethod post = new PostMethod("http://babelfish.yahoo.com/translate_txt"); post.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8"); post.addRequestHeader("Accept-Charset", "ISO-8859-1,utf-8"); final NameValuePair[] params = new NameValuePair[] { new NameValuePair("doit", "done"), new NameValuePair("ei", "UTF-8"), new NameValuePair("intl", "1"), new NameValuePair("trtext", phrase), new NameValuePair("lp", LANGUAGES.get(lp.a()) + "_" + LANGUAGES.get(lp.b())), }; post.setRequestBody(params); return post;/*from w w w.j a va 2s .co m*/ }