List of usage examples for org.apache.commons.httpclient.methods PostMethod FORM_URL_ENCODED_CONTENT_TYPE
String FORM_URL_ENCODED_CONTENT_TYPE
To view the source code for org.apache.commons.httpclient.methods PostMethod FORM_URL_ENCODED_CONTENT_TYPE.
Click Source Link
From source file:com.fusesource.demo.controller.Client.java
public static void main(String args[]) throws Exception { Client client = new Client(); PostMethod post = new PostMethod("http://localhost:" + port + "/controller/process"); post.addRequestHeader("Accept", "text/xml"); RequestEntity entity = new StringRequestEntity(DATA, PostMethod.FORM_URL_ENCODED_CONTENT_TYPE, null); post.setRequestEntity(entity);/* ww w . j a va2 s .co m*/ HttpClient httpclient = new HttpClient(); try { System.out.println("Sending data:\n" + DATA); int result = httpclient.executeMethod(post); System.out.println("Response status code: " + result); System.out.println("Response body: "); System.out.println("Response data:\n" + post.getResponseBodyAsString()); } finally { post.releaseConnection(); } System.out.println("\n"); System.exit(0); }
From source file:net.neurowork.cenatic.centraldir.workers.XMLPusher.java
private void pushOrganization(RestUrlManager restUrl, String token) { HttpClient httpclient = XMLRestWorker.getHttpClient(); PostMethod post = new PostMethod(restUrl.getPushOrganizationUrl()); NameValuePair tokenParam = new NameValuePair("token", token); NameValuePair[] params = new NameValuePair[] { tokenParam }; post.addRequestHeader("Accept", "application/xml"); post.setQueryString(params);//w ww . j av a2s .com String content = XmlPushCreator.getInstance().getPushXml(organizacion); try { RequestEntity entity = new StringRequestEntity(content, PostMethod.FORM_URL_ENCODED_CONTENT_TYPE, null); post.setRequestEntity(entity); int result = httpclient.executeMethod(post); logger.info("Response status code: " + result); logger.info("Response body: "); logger.info(post.getResponseBodyAsString()); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage()); } catch (HttpException e) { logger.error(e.getMessage()); } catch (IOException e) { logger.error(e.getMessage()); } finally { post.releaseConnection(); } }
From source file:ensen.controler.DBpediaSpotlightClient.java
private JSONArray getAnnotationsFromSpotlight(Text text, String confiance, String support, String file) { if (confiance == null || confiance.trim() == "") confiance = PropertiesManager.getProperty("CONFIDENCE"); if (support == null || support.trim() == "") support = PropertiesManager.getProperty("SUPPORT"); JSONArray entities = null;// ww w . ja v a 2 s . c om if (local) { double d = Math.random(); if (d > 0.5) API_URL = PropertiesManager.getProperty("DBpediaSpotlightClientLocal"); else API_URL = PropertiesManager.getProperty("DBpediaSpotlightClientLocalCopy"); } else API_URL = PropertiesManager.getProperty("DBpediaSpotlightClient"); SPOTTER = PropertiesManager.getProperty("spotter"); String spotlightResponse = null; try { //System.out.println("Querying API: " + API_URL); //System.err.println(text.text()); /** using post **/ PostMethod post = new PostMethod(API_URL + "rest/annotate/"); NameValuePair[] data = { new NameValuePair("coreferenceResolution", "false"), /**//*new NameValuePair("disambiguator", "Document"),new NameValuePair("spotter", SPOTTER),*/new NameValuePair( "confidence", confiance), new NameValuePair("support", support), new NameValuePair("text", text.text()) }; post.setRequestBody(data); post.addRequestHeader(new Header("Accept", "application/json")); post.setRequestHeader("Content-Type", PostMethod.FORM_URL_ENCODED_CONTENT_TYPE + "; charset=UTF-8"); spotlightResponse = request(post); } catch (Exception e) { System.err.println("error in calling Spotlight."); } JSONObject resultJSON = null; try { resultJSON = new JSONObject(spotlightResponse); if (resultJSON.has("Resources")) { entities = resultJSON.getJSONArray("Resources"); } else { System.err.println("No founded resources"); System.err.println(resultJSON); } } catch (JSONException e) { System.err.println(spotlightResponse); System.err.println("Received invalid response from DBpedia Spotlight API."); e.printStackTrace(); } if (resultJSON != null) { //System.err.println("print json to" + file + ".json"); //Printer.printToFile(file + ".json", resultJSON.toString()); } //if not enough resources ==> re-do with conf 0.15 if ((entities == null || entities.length() < Integer .parseInt(PropertiesManager.getProperty("MinNofAnnotatedResourcesInDocument"))) && confiance != "0.15") { entities = getAnnotationsFromSpotlight(text, "0.15", support, file); } return entities; }
From source file:com.buzzdavidson.spork.client.OWAClient.java
/** * Perform login to OWA server given configuration parameters and supplied user/password * * @param userName user name for login/*from ww w. java 2s .c o m*/ * @param password password for login * @return true if successfully authenticated */ public boolean login(String userName, String password) { /** * Set NT credentials on client */ Credentials cred; cred = new NTCredentials(userName, password, authHost, authDomain); client.getState().setCredentials(new AuthScope(authHost, AuthScope.ANY_PORT), cred); String authUrl = getBaseUrl() + loginPath; boolean retval = false; logger.info(String.format("Logging in to OWA using username [%s] at URL [%s] ", userName, authUrl)); PostMethod post = new PostMethod(authUrl); post.setRequestHeader(PARAM_CONTENT_TYPE, PostMethod.FORM_URL_ENCODED_CONTENT_TYPE); post.addParameter(PARAM_DEST, getBaseUrl() + docBasePath); post.addParameter(PARAM_UNAME, userName); post.addParameter(PARAM_PWD, password); post.addParameter(PARAM_FLAGS, publicComputer ? OWA_FLAG_VALUE_PUBLIC.toString() : OWA_FLAG_VALUE_PRIVATE.toString()); int status = 0; try { status = client.executeMethod(post); if (logger.isDebugEnabled()) { logger.debug("Post returned status code " + status); } } catch (Exception ex) { logger.error("Got error posting to login url", ex); } if (status == HttpStatus.SC_OK) { // We shouldn't see this in normal operation... Evaluate whether this actually ever occurs. logger.info("Login succeeded (no redirect specified)"); retval = true; } else if (status == HttpStatus.SC_MOVED_TEMPORARILY) { // We typically receive a redirect upon successful authentication; the target url is the user's inbox Header locationHeader = post.getResponseHeader(HEADER_LOCATION); if (locationHeader != null) { String mbxRoot = getMailboxRoot(locationHeader.getValue()); if (mbxRoot == null || mbxRoot.length() < 1) { logger.info("Login failed - Check configuration and credentials."); retval = false; } else { owaRootUrl = mbxRoot; inboxAddress = owaRootUrl + "/" + FOLDER_NAME_INBOX; // TODO is this sufficient? logger.info("Login succeeded, redirect specified (redirecting to " + owaRootUrl + ")"); retval = true; } } } else { logger.error("Login failed with error code " + status); } return retval; }
From source file:com.temenos.interaction.example.odata.notes.CreateReadUpdateDeleteITCase.java
/** * Tests create with application/x-www-form-urlencoded request Content-Type. * //ww w . ja v a 2s.c o m * @throws HttpException * @throws IOException */ @Test public void testCreateUrlEncodedForm() throws HttpException, IOException { ODataConsumer consumer = ODataJerseyConsumer.newBuilder(Configuration.TEST_ENDPOINT_URI).build(); EdmDataServices metadata = consumer.getMetadata(); HttpClient client = new HttpClient(); PostMethod postMethod = new PostMethod(Configuration.TEST_ENDPOINT_URI + PERSONS_RESOURCE); postMethod.setRequestEntity( new StringRequestEntity("name=RonOnForm&abcd=", "application/x-www-form-urlencoded", "UTF-8")); postMethod.addRequestHeader("Content-Type", PostMethod.FORM_URL_ENCODED_CONTENT_TYPE); postMethod.addRequestHeader("Accept", "application/atom+xml"); String personId = null; try { client.executeMethod(postMethod); assertEquals(201, postMethod.getStatusCode()); InputStream is = postMethod.getResponseBodyAsStream(); InputStreamReader isr = new InputStreamReader(is); char[] buffer = new char[1]; int read = 0; int offset = 0; while ((read = isr.read(buffer, offset, buffer.length - offset)) != -1) { offset += read; if (offset >= buffer.length) { buffer = Arrays.copyOf(buffer, buffer.length * 2); } } char[] carr = Arrays.copyOf(buffer, offset); int checkEOF = is.read(); assertEquals(-1, checkEOF); String str = new String(carr); assertEquals("application/atom+xml", postMethod.getResponseHeader("Content-Type").getValue()); FormatParser<Entry> parser = FormatParserFactory.getParser(Entry.class, FormatType.ATOM, new Settings(ODataConstants.DATA_SERVICE_VERSION, metadata, PERSON_ENTITYSET_NAME, null, null)); Entry entry = parser.parse(new StringReader(str)); personId = entry.getEntity().getProperty("id").getValue().toString(); assertEquals("RonOnForm", entry.getEntity().getProperty("name").getValue().toString()); } finally { postMethod.releaseConnection(); } assertNotNull(personId); // read the person to check it was created ok OEntity person = consumer.getEntity(PERSON_ENTITYSET_NAME, Integer.valueOf(personId)).execute(); assertTrue(person != null); assertEquals("RonOnForm", person.getProperty("name").getValue()); }
From source file:com.seajas.search.contender.service.enricher.EnricherService.java
/** * Send the actual envelope content to the enricher. * // ww w.jav a 2 s .c o m * @param jobName * @param encoding * @param request * @return boolean */ public boolean sendEnvelope(final String jobName, final String encoding, final String request) { HttpPost importMethod = new HttpPost(searchEnricherUrl); List<NameValuePair> importParameters = new ArrayList<NameValuePair>(); importParameters.add(new BasicNameValuePair("action", "ImportEnvelope")); importParameters.add(new BasicNameValuePair("JobName", jobName)); if (encoding != null && !encoding.equals(ENCODING_UNKNOWN)) importParameters.add(new BasicNameValuePair("ReferenceEncoding", encoding)); importParameters.add(new BasicNameValuePair("EnvelopeXML", request)); try { importMethod.setEntity(new UrlEncodedFormEntity(importParameters, "UTF-8")); } catch (UnsupportedEncodingException e) { logger.error("Unsupported encoding while encoding the URL form entities", e); } // Set the form encoding to match that of the Search Enricher importMethod.addHeader("Content-Type", PostMethod.FORM_URL_ENCODED_CONTENT_TYPE + ";charset=UTF-8"); boolean result = true; try { if (logger.isTraceEnabled()) logger.trace("Executing the requested envelope post"); // Send the import request HttpResponse importStatus = httpClient.execute(importMethod); if (importStatus.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { logger.error("EnvelopeXML failed to successfully POST, response: " + importStatus.getStatusLine()); result = false; } else { if (logger.isDebugEnabled()) logger.debug("EnvelopeXML succesfully POSTed, response: " + importStatus.getStatusLine()); importMethod.abort(); importMethod = null; } } catch (HttpException e) { logger.error("HTTP execution exception for " + searchEnricherUrl, e); result = false; } catch (IOException e) { logger.error("Resource execution exception for " + searchEnricherUrl, e); result = false; } finally { if (importMethod != null) importMethod.abort(); } return result; }
From source file:com.qlkh.client.server.proxy.ProxyServlet.java
/** * Performs an HTTP POST request//from w w w .ja va 2s . c o m * * @param httpServletRequest The {@link javax.servlet.http.HttpServletRequest} object passed * in by the servlet engine representing the * client request to be proxied * @param httpServletResponse The {@link javax.servlet.http.HttpServletResponse} object by which * we can send a proxied response to the client */ public void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { // Create a standard POST request String contentType = httpServletRequest.getContentType(); String destinationUrl = this.getProxyURL(httpServletRequest); debug("POST Request URL: " + httpServletRequest.getRequestURL(), " Content Type: " + contentType, " Destination URL: " + destinationUrl); PostMethod postMethodProxyRequest = new PostMethod(destinationUrl); // Forward the request headers setProxyRequestHeaders(httpServletRequest, postMethodProxyRequest); setProxyRequestCookies(httpServletRequest, postMethodProxyRequest); // Check if this is a mulitpart (file upload) POST if (ServletFileUpload.isMultipartContent(httpServletRequest)) { this.handleMultipartPost(postMethodProxyRequest, httpServletRequest); } else { if (contentType == null || PostMethod.FORM_URL_ENCODED_CONTENT_TYPE.equals(contentType)) { this.handleStandardPost(postMethodProxyRequest, httpServletRequest); } else { this.handleContentPost(postMethodProxyRequest, httpServletRequest); } } // Execute the proxy request this.executeProxyRequest(postMethodProxyRequest, httpServletRequest, httpServletResponse); }
From source file:com.bluexml.xforms.controller.alfresco.AlfrescoController.java
/** * Request post. Bridge to our XForms webscript under Alfresco. //$$ TRACE * LOG//from ww w . jav a 2 s .co m * * @param transaction * the transaction. MANDATORY and NEVER <code>null</code> * @param parameters * the parameters * @param opCode * the code for the webscript operation being called. * @param dataSourceURI * @return the post method * @throws IOException * Signals that an I/O exception has occurred. * @throws HttpException * the http exception * @throws ServletException */ private PostMethod requestPost(AlfrescoTransaction transaction, Map<String, String> parameters, MsgId opCode, String dataSourceURI) throws IOException, ServletException { // // security: enforce use of possible access controls on the Alfresco side. if (transaction == null) { logger.error("Null transaction."); throw new ServletException("A transaction is required for webscript requests."); } String legitimateLogin = transaction.getLogin(); if (legitimateLogin == null) { legitimateLogin = getParamUserName(transaction.getPage().getInitParams()); } if (StringUtils.trimToNull(legitimateLogin) == null) { logger.error("No user name in the transaction."); throw new ServletException( "Cannot complete the action: a user name is required for webscript requests."); } // // log some info if (loggertrace.isTraceEnabled()) { logger.trace("Calling the webscript for user '" + legitimateLogin + "' with request: " + opCode); logger.trace("Parameters : "); Set<Entry<String, String>> entrySet2 = parameters.entrySet(); for (Entry<String, String> entry2 : entrySet2) { String value = entry2.getValue(); if (value == null) { value = NULL_STRING; } else if (value.equals("")) { value = EMPTY_STRING; } logger.trace(" " + entry2.getKey() + " = " + value); } } // set url String url; boolean useDataSource = dataSourceURI != null && dataSourceURI.startsWith("http"); if (useDataSource) { // it's possible that url have parameters so to avoid conflic with sidereader parameters '&' is replaced by '#' url = dataSourceURI.replaceAll("@\\$@", "&"); } else { url = ALFRESCO_XFORMS_URL + opCode; } PostMethod post = new PostMethod(url); if (!useDataSource) { Set<Entry<String, String>> entrySet = parameters.entrySet(); for (Entry<String, String> entry : entrySet) { post.setParameter(entry.getKey(), entry.getValue()); } // if (StringUtils.trimToNull(transaction.getLogin()) == null) { // post.setParameter("username", getParamLoginUserName(transaction.getInitParams())); // } else { // post.setParameter("username", transaction.getLogin()); // } post.setParameter("username", transaction.getLogin()); post.setParameter("serviceCallerId", "XFormsController"); post.setParameter("serviceCallerVersion", "2.0.0"); } else { Gson gson = new Gson(); String json = gson.toJson(parameters); post.setParameter("xformsParameters", json); } post.addRequestHeader("Content-Type", PostMethod.FORM_URL_ENCODED_CONTENT_TYPE + "; charset=UTF-8"); executeMethod(post, false); if (loggertrace.isTraceEnabled()) { logger.trace("Response : "); String responseBodyAsString = post.getResponseBodyAsString(); if (responseBodyAsString == null) { logger.trace(NULL_STRING); } else if (responseBodyAsString.equals("")) { logger.trace(EMPTY_STRING); } else { logger.trace(responseBodyAsString); } } return post; }
From source file:org.apache.ode.axis2.httpbinding.HttpMethodConverter.java
/** * create and initialize the http method. * Http Headers that may been passed in the params are not set in this method. * Headers will be automatically set by HttpClient. * See usages of HostParams.DEFAULT_HEADERS * See org.apache.commons.httpclient.HttpMethodDirector#executeMethod(org.apache.commons.httpclient.HttpMethod) *//* w w w. j av a 2 s . c o m*/ protected HttpMethod prepareHttpMethod(BindingOperation opBinding, String verb, Map<String, Element> partValues, Map<String, Node> headers, final String rootUri, HttpParams params) throws UnsupportedEncodingException { if (log.isDebugEnabled()) log.debug("Preparing http request..."); // convenience variables... BindingInput bindingInput = opBinding.getBindingInput(); HTTPOperation httpOperation = (HTTPOperation) WsdlUtils.getOperationExtension(opBinding); MIMEContent content = WsdlUtils.getMimeContent(bindingInput.getExtensibilityElements()); String contentType = content == null ? null : content.getType(); boolean useUrlEncoded = WsdlUtils.useUrlEncoded(bindingInput) || PostMethod.FORM_URL_ENCODED_CONTENT_TYPE.equalsIgnoreCase(contentType); boolean useUrlReplacement = WsdlUtils.useUrlReplacement(bindingInput); // the http method to be built and returned HttpMethod method = null; // the 4 elements the http method may be made of String relativeUri = httpOperation.getLocationURI(); String queryPath = null; RequestEntity requestEntity; String encodedParams = null; // ODE supports uri template in both port and operation location. // so assemble the final url *before* replacement String completeUri = rootUri; if (StringUtils.isNotEmpty(relativeUri)) { completeUri = completeUri + (completeUri.endsWith("/") || relativeUri.startsWith("/") ? "" : "/") + relativeUri; } if (useUrlReplacement) { // insert part values in the url completeUri = new UrlReplacementTransformer().transform(completeUri, partValues); } else if (useUrlEncoded) { // encode part values encodedParams = new URLEncodedTransformer().transform(partValues); } // http-client api is not really neat // something similar to the following would save some if/else manipulations. // But we have to deal with it as-is. // // method = new Method(verb); // method.setRequestEnity(..) // etc... if ("GET".equalsIgnoreCase(verb) || "DELETE".equalsIgnoreCase(verb)) { if ("GET".equalsIgnoreCase(verb)) { method = new GetMethod(); } else if ("DELETE".equalsIgnoreCase(verb)) { method = new DeleteMethod(); } method.getParams().setDefaults(params); if (useUrlEncoded) { queryPath = encodedParams; } // Let http-client manage the redirection // see org.apache.commons.httpclient.params.HttpClientParams.MAX_REDIRECTS // default is 100 method.setFollowRedirects(true); } else if ("POST".equalsIgnoreCase(verb) || "PUT".equalsIgnoreCase(verb)) { if ("POST".equalsIgnoreCase(verb)) { method = new PostMethod(); } else if ("PUT".equalsIgnoreCase(verb)) { method = new PutMethod(); } method.getParams().setDefaults(params); // some body-building... final String contentCharset = method.getParams().getContentCharset(); if (log.isDebugEnabled()) log.debug("Content-Type [" + contentType + "] Charset [" + contentCharset + "]"); if (useUrlEncoded) { requestEntity = new StringRequestEntity(encodedParams, PostMethod.FORM_URL_ENCODED_CONTENT_TYPE, contentCharset); } else { // get the part to be put in the body Part part = opBinding.getOperation().getInput().getMessage().getPart(content.getPart()); Element partValue = partValues.get(part.getName()); if (part.getElementName() == null) { String errMsg = "XML Types are not supported. Parts must use elements."; if (log.isErrorEnabled()) log.error(errMsg); throw new RuntimeException(errMsg); } else if (HttpUtils.isXml(contentType)) { if (log.isDebugEnabled()) log.debug("Content-Type [" + contentType + "] equivalent to 'text/xml'"); // stringify the first element String xmlString = DOMUtils.domToString(DOMUtils.getFirstChildElement(partValue)); requestEntity = new StringRequestEntity(xmlString, contentType, contentCharset); } else { if (log.isDebugEnabled()) log.debug("Content-Type [" + contentType + "] NOT equivalent to 'text/xml'. The text content of part value will be sent as text"); // encoding conversion is managed by StringRequestEntity if necessary requestEntity = new StringRequestEntity(DOMUtils.getTextContent(partValue), contentType, contentCharset); } } // cast safely, PUT and POST are subclasses of EntityEnclosingMethod final EntityEnclosingMethod enclosingMethod = (EntityEnclosingMethod) method; enclosingMethod.setRequestEntity(requestEntity); enclosingMethod .setContentChunked(params.getBooleanParameter(Properties.PROP_HTTP_REQUEST_CHUNK, false)); } else { // should not happen because of HttpBindingValidator, but never say never throw new IllegalArgumentException("Unsupported HTTP method: " + verb); } method.setPath(completeUri); // assumes that the path is properly encoded (URL safe). method.setQueryString(queryPath); // set headers setHttpRequestHeaders(method, opBinding, partValues, headers, params); return method; }
From source file:org.codeartisans.proxilet.Proxilet.java
/** * Performs an HTTP POST request./* ww w .j ava2 s . co m*/ * * @param httpServletRequest The {@link HttpServletRequest} object passed in by the servlet engine representing the client request to be proxied * @param httpServletResponse The {@link HttpServletResponse} object by which we can send a proxied response to the client */ @Override public void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { // Create a standard POST request String contentType = httpServletRequest.getContentType(); String destinationUrl = this.getProxyURL(httpServletRequest); LOGGER.trace("POST {} => {} ({})" + httpServletRequest.getRequestURL(), destinationUrl, contentType); PostMethod postMethodProxyRequest = new PostMethod(destinationUrl); // Forward the request headers setProxyRequestHeaders(httpServletRequest, postMethodProxyRequest); // Check if this is a mulitpart (file upload) POST if (ServletFileUpload.isMultipartContent(httpServletRequest)) { this.handleMultipartPost(postMethodProxyRequest, httpServletRequest); } else { if (contentType == null || PostMethod.FORM_URL_ENCODED_CONTENT_TYPE.equals(contentType)) { this.handleStandardPost(postMethodProxyRequest, httpServletRequest); } else { this.handleContentPost(postMethodProxyRequest, httpServletRequest); } } // Execute the proxy request this.executeProxyRequest(postMethodProxyRequest, httpServletRequest, httpServletResponse); }